System.gc() Invocation – A Suitable Scenario

System.gc() is used to invoke the garbage collector and on invocation garbage collector will run to reclaim the unused memory space. It will attempt to free the memory that are occupied by the discarded objects. However System.gc() call comes with a disclaimer that invocation of the garbage collector is not guaranteed. We have got used to the ‘conditions apply’ with our experiences from the real world. Everything comes with a disclaimer!

It is the choice of JVM implementer to decide the behavior of JVM on System.gc() invocation. In general we do not think about memory management when writing our Java code and leave it to the JVM. In some special cases like when we are writing a performance benchmark we may call System.gc() in between runs. Following is another example where invoking gc makes a difference.

MappedByteBuffer

MappedByteBuffer is used at places where we need the best IO performance. MappedByteBuffer provides a direct memory mapping to the underlying File.

API Javadoc says,

Many of the details of memory-mapped files are inherently dependent upon the underlying operating system and are therefore unspecified. The behavior of this method when the requested region is not completely contained within this channel’s file is unspecified. Whether changes made to the content or size of the underlying file, by this program or another, are propagated to the buffer is unspecified. The rate at which changes to the buffer are propagated to the file is unspecified.

Almost everything is unspecified and left to the underlying OS. Let us look at the following code,

In the above code, line number 24 System.gc() is commented. When I run this program now, always I get “Unable to delete: … “. Now lets uncomment the System.gc() and re-run it multiple times to understand the behavior. Now we get “Successfully deleted: …” most of the times. I tested the same with just ByteBuffer and garbage collection happens nice and immediate.

‘Looks like’ since the MappedByteBuffer is heavily OS dependent, the garbage collector is not instantaneous to reclaim. But when we invoke System.gc() garbage collector releases the handle and we are able to delete the file. Shall we make an inference that, “while using MappedByteBuffer and if we are working with memory sensitive program, then its better to call System.gc()”. Note that this behavior is JVM dependent.

Wishing you a happy and prosperous 2014. Thank you for your support to Javapapers all these years and looking forward to your continued patronage. I am feeling fresh and you can expect better articles than ever. Java 8 is coming up and lot more to discover.

Hi Joe,
I m too late but I want to know whether the file will get deleted instantly if it shows “Successfully Deleted” or not. As I ran the program but the file was still there with the name Temp*************.tmp