views:

466

answers:

14
  • Do you always assign null to an object after its scope has been reached?

  • Or do you rely on the JVM for garbage collection?

  • Do you do it for all sort of applications regardless of their length?

  • If so, is it always a good practice?

+5  A: 
  • no, don't do that, except for specific cases such as static fields or when you know a variable/field lives a lot longer than the code referencing it
  • yes, but with a working knowledge of your VM's limits (and how to cause blocks of memory to be held accidentally)
  • n/a
Marc Gravell
It should be "the objects it references" rather than "the code (objects) referencing it". An object may be collected while it references other objects, but not the other way round.
sfussenegger
@sfussenegger: "An object may be collected while it references other objects, but not the other way round.". What about a cyclic reference?
Adamski
anything not accessible from a "root" is eligle for garbage collections, cyclical or not.
TofuBeer
JVMs have had various sorts of garbage collection. Reference counting is the easiest to implement, and IIRC was used early on, and it's stymied by circular references. More sophisticated and harder to implement algorithms determine if something's reachable no matter what.
David Thornley
+9  A: 

It's not necessary to explicitly mark objects as null unless you have a very specific reason. Furthermore, I've never seen an application that marks all objects as null when they are no longer needed. The main benefit of garbage collection is the intrinsic memory management.

Taylor Leese
-1 you *must* worry, regardless of garbage collection being available or not
sfussenegger
To give an example: don't keep references to session objects in your application class (e.g. in a Map) as you will prevent garbage collection until you'll finally run out of memory.
sfussenegger
i think you took my wording too literal
Taylor Leese
what i meant is that most of the time the standard GC functionality will do what you need
Taylor Leese
Taylor gave the caveat of a specific reason.
Jonathon
updated my verbaige to be less confusing
Taylor Leese
I agree, most of the time that's true. But saying "The main benefit of garbage collection is not having to worry about memory management" is a common mistake. People tend to overestimate the capabilities of GC - hence the downvote. If you rephrase your sentence and I'll take it back.
sfussenegger
i just did that to appease you since the way you interpreted my comment was not what i intended
Taylor Leese
0 no longer a -1, but still no +1 ;)
sfussenegger
"unless you have a very special reason." - that reason should be put in a comment next to the assignment!
Thorbjørn Ravn Andersen
A: 

When using the .Net I don't think there's a need to set the object to null. Just let the garbage collection happen.

jbloomer
+2  A: 

Assignin null to a variable does not implicitly mean it will be garbage collected right away. In fact it most likely won't be. Whether you practice setting variables to null is usually only cosmetic (with the exception of static variables)

Miky Dinescu
+2  A: 

Garbage collection is not as magical as you might expect. As long as an object is referenced from any reachable object it simply can't be collected. So it might be absolutely necessary to null a reference in order to avoid memory leaks. I don't say you should do this always, but always when it's necessary.

sfussenegger
+1  A: 

As the others have mentioned, it's not usually necessary.

Not only that, but it clutters up your code and increases the data someone needs to read and understand when revisiting your code.

Jonathon
+2  A: 

We don't practice this assigning "null". If a variable's scope has reached it's end it should already be ready for GC. There may be some edge cases in which the scope lasts for a while longer due to a long running operation in which case it might make sense to set it to null, but I would imagine they would be rare.

It also goes without saying that if the variable is an object's member variable or a static variable and hence never really goes out of scope then setting it to null to GC is mandatory.

Matt
+1  A: 

Assigning is not done to objects, it is done to variables, and it means that this variable then holds a reference to some object. Assigning NULL to a variable is not a way to destroy an object, it just clears one reference. If the variable you are clearing will leave its scope afterwards anyway, assigning NULL is just useless noise, because that happens on leaving scope in any case.

Svante
+5  A: 

I declare almost all of my variables as "final". I also make my methods small and declare most variables local to methods.

Since they are final I cannot assign them null after use... but that is fine since the methods are small the objects are eligible for garbage collection once they return. Since most of the variables are local there is less chance of accidentally holding onto a reference for longer than needed (memory leak).

TofuBeer
+1  A: 

The one time I tend to use this practice is if I need to transform a large Collection in some early part of a method.

For example:

public void foo() {
  List<? extends Trade> trades = loadTrades();
  Map<Date, List<? extends Trade>> tradesByDate = groupTradesByDate(trades);
  trades = null; // trades no longer required.

  // Apply business logic to tradesByDate map.
}

Obviously I could reduce the need for this by refactoring this into another method: Map<Date, List<? extends Trade>>> loadTradesAndGroupByDate() so it really depends on circumstances / clarity of code.

Adamski
The above can be shortened as groupTradesByDate(loadTrades()) and then the variable is no longer needed at all.
Kevin Panko
@Kevin - Agreed. Perhaps I made this example too simple :-)
Adamski
Your point is still valid -- sometimes it might make sense to do this.
Kevin Panko
A: 

- Do you always assign null to an object after its scope has been reached?

No

- Or do you rely on the JVM for garbage collection?

Yes

- Do you do it for all sort of applications regardless of their length?

Yes

- If so, is it always a good practice?

N/A

OscarRyz
+1  A: 

I only assign a reference to null when:

  1. The code really lies in a memory-critical part.
  2. The reference has a wide scope (and must be reused later). If it is not the case I just declare it in the smallest possible code block. It will be available for collection automatically.

That means that I only use this technique in iterative process where I use the reference to store incoming huge collection of objects. After processing, I do not need the collection any more but I want to reuse the reference for the next collection.

In that case (and only in that case), I then call System.gc() to give a hint to the Garbage Collector. I monitored this technique through heap visualizer and it works very well for big collections (more then 500Mb of data).

paradigmatic
A: 

I assume you're asking this question because you've seen code with variables being assigned to null at the point where they will never be accessed again.

I dislike this style, but another programmer used it extensively, and said he was taught to do so at a programming course at his university. The reasoning he gave is that it would prevent undetectable bugs if he tried to reuse the variable later on, instead of indeterminate behavior, he'd get a null pointer exception.

So if you're prone to using variables where you shouldn't be using variables, it might make your code more easy to debug.

ironchefpython
Similarly, some people set C++ pointers to null after deleting them.
David Thornley
A: 

There was a class of memory leak bugs that happened regardless of whether I set the reference to null - if the library I was using was written in a language like C without memory management, then simply setting the object to null would not necessarily free the memory. We had to call the object's close() method to release the memory (which, of course, we couldn't do after setting it to null.)

It thus seems to me that the de facto method of memory management in java is to rely on the garbage collector unless the object/library you're using has a close() method (or something similar.)

steve