Possible Duplicate:
Does setting Java objects to null do anything anymore?
I am using a same variable again and again in a method & referring it to a new object at many a times.. Is it a good practice from garbage collection aspect to nullify it before making it refer a new object.
Example:
StopWatch watch = new StopWatch();
watch.start();
//some code
watch.stop();
//some code
watch = null;
watch = new StopWatch();
watch.start();
//some code
watch.stop();
//some code
Not sure whether nullifying it make a difference to GC in this case. Please guide.
Thanks!
Assigning
nullat that point will make no difference, because you are immediately going to assign a new value to that variable.There is nothing “magical” in Java about assigning
nullto a variable. It doesn’t cause the object to be garbage collected immediately. All it is doing is breaking one of (possibly) many “paths” by which the object in question is reachable. If the path would break / disappear of its own accord before the next GC run, then assigningnullachieves nothing.Normally it is not worth nulling variables or fields in Java, and it is certainly not worth doing for a local variable is about to be overwritten, or is about to go out of scope.