Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must you set references to null for garbage collection to work

Tags:

java

memory

jvm

Hi i am attempting to discover why my program's usually run slower than i want them so thank you in advance for your help!


I have for example a piece of code that i would like some insight into
1. while(conditionIsTrue){
2.      Object object = new Object();
3.  }

in Line #2. I create a new Object. This will happen thousands of times in my program. Do i specifically have to null the old Object out before gc will destroy it? Or will gc go behind my program picking up all the memory those other Objects used.

Or another option altogether is this happening: A certain amount of memory is being allocated and every time i create a new Object it is then assigned to that exact same memory.


Bruno asked me to show a more realistic piece of code so we could figure out why it was running slowly. But, because of your answer Bruno i realized that i had my code like this
1. Object object = null;
2. while(conditionIsTrue){
3.      object = new Object();
4.  }

So i realized i had Strong references to my Objects. Thank you Bruno!

like image 712
snocavotia Avatar asked Jun 25 '13 00:06

snocavotia


1 Answers

In this case, you don't need to object = null; to allow the GC to clear the new Object(), since there are no references left to the object right after the iteration that instantiated the object finishes (that is, line #3).

The rule is: the GC is allowed to clear an object whenever there are no more strong references pointing to it. It might not clear the object right away, it might take some time, but unless you manage to acquire new strong references to it (yes, there are ways! see SoftReference and WeakReference for example), it will eventually be cleared, and certainly before it throws an OutOfMemoryError.

Also, the JVM is very smart about allocating memory. There's something called escape analysis: it allows the JVM to understand that the new Object() is not used anywhere outside that loop, so it may even allocate the memory for the object right on the stack, not on the heap! Therefore, it might be the case that no GC is needed at all for that specific object -- when the method finishes, the object is automatically cleared.

I would even guess that the JVM might detect that instantiating that object has absolutely no noticeable effect at all, and might even simply chose not to run that line #2 (but this is a guess, and an optimization I might think about doing if I were writing a compiler -- if someone knows for sure if this happens or does not happen, please add a comment!).

If your program is running slower than you'd like it run, then you'd have to show some more realistic code. Something that you might consider a subtle difference between your real code and the snippet you asked about might be a huge difference for the JVM!

like image 142
Bruno Reis Avatar answered Oct 13 '22 02:10

Bruno Reis