Saturday, 6 August 2011

Garbage collection in Java

What is garbage collection and who handles it?
is the process of collecting unused/unreachable objects (i.e those objects who have lived their life in the lifetime of a program and whose non existence does not affect the continuity of the program). Java handles memory de-allocation through garbage collection. There is a low priority daemon thread called the Garbage Collector thread which runs in the background performing this task of collecting unreachable objects. It runs in low memory situations to reclaim unused memory. Garbage collection cannot be forced, you can request the JVM to perform GC through System.gc(), but there is no guarantee that it will be a synchronous call or it will happen immediately on call.


Why does GC happen?
Whenever the JVM runs low in memory /or during certain time intervals, the garbage collector thread will wake up and try to reclaim unused memory by de-allocating memory referenced by unreachable object. Every programmer must have experienced a behavior of sudden unresponsiveness in the lifetime of a program. These are times when the garbage collector is doing its job of reclaiming memory. If the JVM cannot create an object on the heap it will fail with OutOfMemoryError.


When does an object become eligible for GC?
We know that in java an object that gets created, lives on the heap, whether the object is a local variable or instance variable, where as class or static variables live inside the memory area (fyi).
When an object becomes unreachable it becomes eligible for GC. (i.e no live threads or static references point to these object)
So when does object become unreachable.

  1. When you explicitly assign all references to an object to null, stating that the object has served its purpose and is no longer needed.
  2. Object goes out of scope once the block of code in which it is created gets executed.
  3. Cyclic references are detected by garbage collecting algorithms and hence become automatically eligible for garbage collection as long as there are no other live object referencing these objects.
  4. When the container object is set to null , the contained objects become eligible for GC.
  5. All weak reference gets eligible for GC in the next GC cycle.

References

No comments:

Post a Comment