Devashish Devashish - 1 year ago 40
Java Question

When to explicitly set objects to null in order to make the memory reclaimable in Java?

I found the following in the book that I use to learn Java:

The garbage collector only frees memory that is allocated using

. But it has no knowledge of memory that is allocated using other methods. So, the gc cannot reclaim it. An example of such memory allocation would be native methods in Java.

I don't have the exact wording right now but the book has something like that when it explains Objects in detail. The book only provides a single example of such a case where GC can't reclaim memory for us. I am sure there are other situations when this happens. Can someone please list some of them as that would help us know when to set objects to null, explicitly and when it is okay to rely on GC.

Answer Source

Pretty much everything other than primitives and Strings are instantiated with a new. And you should not be worried about Garbage collection to the extent that you have to set variables to null to make them eligible. GC has become very intelligent in last few years that we don't have to resort these tricks. e.g. Any orphaned object in heap ( which is not referred by anything) is a GC candidate. If you have your code structured, all method scope objects are GC candidate once the method has finished execution, same with a state variable as soon as the object of the class itself is dereferenced.