Alex Rivera | Logout

Does assigning objects to null in Java impact garbage collection?

Asked 2009-01-16T03:30:02.797
89

Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

Edit
Report

3 Answers

7

It depends.

Generally speaking shorter you keep references to your objects, faster they'll get collected.

If your method takes say 2 seconds to execute and you don't need an object anymore after one second of method execution, it makes sense to clear any references to it. If GC sees that after one second, your object is still referenced, next time it might check it in a minute or so.

Anyway, setting all references to null by default is to me premature optimization and nobody should do it unless in specific rare cases where it measurably decreases memory consuption.

answered 2009-01-16T03:50:14.910
4

I was working on a video conferencing application one time and noticed a huge huge huge difference in performance when I took the time to null references as soon as I didn't need the object anymore. This was in 2003-2004 and I can only imagine the GC has gotten even smarter since. In my case I had hundreds of objects coming and going out of scope every second, so I noticed the GC when it kicked in periodically. However after I made it a point to null objects the GC stopped pausing my application.

So it depends on what your doing...

answered 2012-12-09T17:33:28.813
0

Yes.

From "The Pragmatic Programmer" p.292:

By setting a reference to NULL you reduce the number of pointers to the object by one ... (which will allow the garbage collector to remove it)

answered 2009-01-16T03:35:51.707

Your Answer