System.gc Invocation For Garbage Collection

Garbage collection is the process of reclaiming the used memory which is no more reference objects in the application. Java Virtual Machine (JVM) runs the background thread for monitoring the object references and runs periodically to claim the memory. This thread runs on the low priority since the performance of JVM will be impacted while running this thread which stops all other threads for few seconds. System.gc()  is the method which suggests the garbage collection to the JVM. However, this is not guaranteed.

System.gc() is implemented by the VM, and what it does is implementation specific. The implementer could simply return and do nothing, for instance.

Look at the below simple example.

package javabeat.net.system;
import java.lang.*;
public class GCDemo {
   public static void main(String[] args) {
     int arr1[] = { 0, 10, 20, 30, 40, 50 };
     int arr2[] = { 0, 100, 200, 300, 400, 500 };

     System.arraycopy(arr1, 0, arr2, 0, 1);
     System.out.print("array2 = ");
     System.out.print(arr2[0] + " ");
     System.out.println(arr2[1] + " ");

     // it runs the GarbageCollector
     System.gc();
     System.out.println("Cleanup completed...");
   }
}

If you look at the above example, there is chance of calling the JVM to reclaim the memory. However, it is not guaranteed to run at the specified time. Also it depends on the JVM implementation vendor who chooses the appropriate time for calling the garbage collection. The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc(). This is the reason of this “may or may not decide to do a GC at that point”.

Now, if you look at OpenJDK source code, which is the backbone of Oracle JVM, you will see that a call to System.gc() does start a GC cycle. If you use another JVM, such as J9, you have to check their documentation to find out the answer. For instance, Azul’s JVM has a garbage collector that runs continuously, so a call to System.gc() won’t do anything

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*