Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like malloc/free in java?

I've never seen such statements though,does it exist in java world at all?

like image 621
java Avatar asked Dec 10 '10 01:12

java


3 Answers

Java's version of malloc is new -- it creates a new object of a specified type.

In Java, memory is managed for you, so you cannot explicitly delete or free an object.

like image 67
ClosureCowboy Avatar answered Oct 15 '22 10:10

ClosureCowboy


new instead of malloc, garbage collector instead of free.

like image 28
kriss Avatar answered Oct 15 '22 09:10

kriss


No direct equivalents exist in Java:

C malloc creates an untyped heap node and returns you a pointer to it that allows you to access the memory however you want.

Java does not have the concept of an untyped object, and does not allow you to access memory directly. The closest that you can get in Java to malloc would be new byte[size], but that returns you a strongly typed object that you can ONLY use as a byte array.

C free releases a heap node.

Java does not allow you to explicitly release objects. Object deallocation in Java is totally in the hands of the garbage collector. In some cases you can influence the behaviour of the GC; e.g. by assigning null to a reference variable and calling System.gc(). However, this does not force the object to be deallocated ... and is a very expensive way to proceed.

like image 31
Stephen C Avatar answered Oct 15 '22 10:10

Stephen C