Wednesday, June 19, 2013

Forcing Java virtual machine to run garbage collector

No, You cant force garbage collection.
Even using
You can just make a request for garbage collection but it depends on JVM to do it or not.
Also Garbage collector are smart enough to collect unused memory when required so instead of forcing garbage collection you should check if you are handling objects in a right way.
If you are handling objects in a wrong way (like keeping reference to unnecessary objects) there is hardly anything JVM can do to free the memory. 

From Doc 
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. 
Which means that garbage collector makes best possible effort but it is not guaranteed that it will free up the space every-time.  

Bug regarding System.gc() documentation 
The documentation for System.gc() is extremely misleading and fails to make reference to the recommended practise of never calling System.gc().
The choice of language leaves it unclear what the behaviour would be when System.gc() is called and what external factors will influence the behaviour.
 Few useful links to visit when you think you should force JVM to free up some memory
1. How does garbage collection work
2. System.gc() in Java
3. Why is it a bad practice to call System.gc?  

All says
1. You don't have control over Garbage Collection in Java even System.gc() dont guarantee it.
2. Also its bad practice as forcing it may have adverse effect on performance.
3. Revisit your design and let JVM do his work :)

No comments:

Post a Comment