Saturday 15 February 2014

Garbage Collection

JVM heap stores the objects created by an Application. In languages like “C”, You must explicitly free the memory by using free(), but in Java JVM takes care these tasks. No way you can explicitly free the memory in Java. Everything is done by JVM.

Garbage collection is a process of freeing memory used by un referenced objects.

A disadvantage of garbage-collected heap is that it adds an overhead that can affect program performance. Since in background, the Java Garbage collector thread keeps track of the objects like which are in use and which are not reference by any other etc.,

JVM perform the Garbage collection periodically, but you can suggest the JVM, to perform Garbage collection immediately by using “System.gc()”. But it is not guaranteed to run Garbage collection immediately, It is just a suggestion went to run Garbage Collector. It is the JVM, to decide how to respond for the request.

System.gc
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Implementation of gc in System class
public static void gc() {
    Runtime.getRuntime().gc();
}

Simply it is calling the gc method of Runtime class. So the call System.gc() is equivalent to the call:
Runtime.getRuntime().gc()

Some Points to Remember
1. is calling to System.gc() runs the garbage collector immediately ?
No, Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

2. What is the difference between gc() in System class and Runtime class?
No difference. System.gc() calls the gc() of Runtime class internally.

3. Is garbage collector a dameon thread?
Yes, Garbage collector runs as a background thread

4. When does an object become eligible for garbage collection?
An object becomes eligible for Garbage Collection when no references can access it, I.e, reference count for the object is zero.


You may like
Object creation and destruction                                                 main method                                                 Home

No comments:

Post a Comment