In Java, is there a way to mark an object for garbage collection by the GC, during its next clean up cycle?
I\'ve heard that setting an object to
You heard wrong, but then again the description is wrong too.
You don't set an object to null
, you set a variable to null
. If the variable can be used to get to an object, then the variable has a reference to the object. Setting the variable to null
is the same as the variable "losing the reference" to the object.
Once Java detects that an object, or a group of objects can't be reached by the running program, it will remove those objects from memory. It won't remove them from memory one moment sooner, because if it did, and some other part of the program tried to use a reference to the object, then the reference would fail in a way that's not permissible in Java.
The trick is not to set just one reference to null
, you have to set all the references that might have been made to null
. That's why it's important to consider each time you create a new reference, because you want to create them in such a manner that they will eventually be cleared (unless you want a memory leak).