Monday 21 September 2015

Runtime.getRuntime().gc() and System.gc()

Garbage Collection in Java is carried by a daemon thread called Garbage Collector. Before removing an object from memory garbage collection thread invokes finalize() method of that object and gives an opportunity to perform required cleanups.

We cannot force garbage collection in Java. It will only trigger if JVM thinks it needs a garbage collection based on Java heap size.

System.gc() and Runtime.gc() are the methods which can be used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.

Runtime.gc()

void java.lang.Runtime.gc()

Calling this method suggests that the JVM 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 JVM has made its best effort to recycle all discarded objects.

The virtual machine performs this recycling process automatically as needed, in a separate thread, even if the gc() method is not invoked explicitly.

The method System.gc() is the conventional and convenient means of invoking this method.

public native void gc();

How to call Runtime.gc()?

Runtime.getRuntime().gc();

Runtime is Singleton Class and getRuntime() returns the instance of this class.

System.gc()

void java.lang.System.gc()

Calling of System.gc() is effectively equivalent to call Runtime.getRuntime().gc();

System.gc() implementation

public static void gc() {
Runtime.getRuntime().gc();
}

System.gc() internally calls the  Runtime.gc().

We don't need to call garbage collection (calling System.gc()) manually because in most circumstances it is harmful for application performance.

When should use System.gc()?

If the application knows it is going into a phase where it has nothing else to do AND the user is unlikely to notice a garbage collection, then maybe it is OK call to System.gc() in an effort to stop the user experiencing GC pauses in the future.

The downsides include:

Calling System.gc() typically triggers a full GC which takes significantly longer than a GC of the 'new space'.

By forcing the GC, you are causing the JVM to use extra CPU cycles, etc. which may potentially interfere with other things that the user is doing on his machine.

2 comments:

Related Posts Plugin for WordPress, Blogger...