SiteMap  | About    

Does assigning objects to null in Java impact garbage collection?

Not necessarily. An object becomes eligible for garbage collection when there are no live threads anymore that hold a reference to the object.

Explicit nulling is simply the practice of setting reference objects to null when you are finished with them. The idea behind nulling is that it assists the garbage collector by making objects unreachable earlier. The GC (Garbage collection) in Java these days is very smart and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

Explicitly setting a reference to null instead of just letting the variable go out of scope, does not help the garbage collector , unless the object held is very large. Local variables go out of scope when the method returns and it makes no sense at all to set local variables to null - the variables disappear anyway, and if there's nothing else that holds a reference the objects that the variables referred to, then those objects become eligible for garbage collection .

The object is reachable if it can be involved in any potential continuing computation. So if your code refers to a local variable, and nothing else refers to it, then you might cause the object to be collected by setting it to null . This would either give a null pointer exception, or change the behaviour of your program, or if it does neither you didn't need the variable in the first place. Tricks such as explicit nulling or object pooling , which were once considered sensible techniques for improving performance, are no longer necessary or helpful (and may even be harmful) as the cost of allocation and garbage collection has been reduced considerably. (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.