3

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!

Community
  • 1
  • 1
Shikha Dhawan
  • 1,414
  • 8
  • 27
  • 44
  • should make no difference – Karthik T Jan 07 '13 at 07:43
  • 2
    Pretty much useless to set a variable to null if the only reason is to mark it such that the GC will delete it. If you new another object and store it in the.same variable then the previous object will be collected when the GC feels like it. So the.code. above works fine even without setting null. – bas Jan 07 '13 at 07:46

4 Answers4

7

Assigning null at 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 null to 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 assigning null achieves 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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

No, nullifying will not make any difference in this case.

It would have made difference had it not been assigned to some other variable immediately. In that case, instead of waiting for the reference to go out of scope, the object would have become eligible for GC.

the GC generally collects those objects which do not have reference. As you are pointing the reference to some other object in memory, the reference to the previous object is anyways lost. Hence there is no difference if you assign null to it or not.

It will be available for garbage collection provider there is no other reference to it

Rahul
  • 15,979
  • 4
  • 42
  • 63
2

When an object is available for garbage collection JVM assign null value to that object.

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.

1

It will not make any difference as you are immediately assigning a new object after nullifying

vishal_aim
  • 7,636
  • 1
  • 20
  • 23