Tuesday, 16 October 2012

Garbage Collection or Memory DeAllocation in Java

Garbage Collection Memory DeAllocation in Java
In Java, an object which is no longer referred by any reference variable will automatically be removed from the memory, this process is known as Garbage Collection. Garbage Collection is automatically done by Java Virtual Machine (JVM), the automatic Garbage Collection of Java de-allocates the dynamic memory when this memory is no more used by the program. Thus the Garabage collection feature of Java relieves the programmer from the overhead of memory de-allocation.(A major difficulty in dynamic memory allocation in C/C++ was that the programmer is responsible for de-allocating the dynamic memory at the right time. Even though experienced programmers can do this very well, beginners and average programmers often miss the statements for de-allocation which leads to memory-leak in many systems.)
How Garbage collection in Java works
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends. Or programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use. And then Garbage collector will claim the memory allotted for that.
Please note: Primitive data types are not objects and they cannot be assigned null.

No comments:

Post a Comment