Java & Programming 05 Oct 2007 01:33 pm
A Good Reasoning to Nullify an Object!
If you overwrite a reference with a new object, the object is first created and /then/ the reference is overwritten, which means the object can be only GCed /after/ the new object has been created.
Usually this doesn’t matter. However, if you want to overwrite an object which is so big that it only fits once into the memory, you’ll need to null the reference before creating/assigning the new instance.
Eg:
//FatObject fits only once into memory
FatObject fatty;
fatty=new FatObject();
fatty=new FatObject();Will bomb with OOME. Whereas…
FatObject fatty;
fatty=new FatObject();
fatty=null;
fatty=new FatObject();Will be fine, because the second creation of the FatObject will trigger a full GC and the GC will be able to clear enough memory (since the old reference has been nulled).
Well, that rarely matters, but it’s good to know.
Jos Hirth wrote this in response to this post by Jeroen van Erp.
In this post, Jeroen was talking about a long standing bug/issue/misunderstanding of how Strings are handled in Java. The problem that occurs only comes up when taking a substring of a large String. If all that is wanted is the small substring, the substring must be wrapped by a new String call. This will allow the larger String to be garbage collected. Normally when a substring is taken, the underlying char array is shared. This is usually good practice, because it saves memory.
But, and this is a big but, if the substring is taken from a large string, then memory can be leaked, because a lot of memory is wasted in the underlying character array.
Now, why did I quote the above passage from the comment area? Cause I had never thought of the issue Jos brought up. It’s interesting to think of an object of which only one can fit in memory. Let alone creating a second!