How does garbage collection work in Java, and what makes an object garbage?
The garbage collector works out what is still reachable and frees everything else.
So what makes an object garbage? It is an object that nothing can reach any more. Not that it is unused, and not that you have finished with it. If no path of references leads from the roots of the program to the object, then it is garbage, and the collector is free to take it.
The roots of the program are the places where a live reference can sit. They are the local variables on the stacks of the threads, the static fields of the loaded classes, the objects that are held by the runtime itself, such as the ones that a thread is waiting on, and the references that were handed to the native code.
public class Main {
public static void main(String[] args) {
// Once nothing references an object, it is eligible for collection.
Object reference = new Object();
System.out.println("the object is here : " + (reference != null));
// The name of the variable is the only thing holding it now.
reference = null;
// The collector will take it at some point. You never see it happen.
System.out.println("the reference is gone");
}
}
So the collector starts at the roots and follows every reference it finds, and everything it reaches is alive. Everything else is garbage.
There are two details that are worth knowing. The first one is that Java does not use reference counting. An earlier language used to count how many things pointed at each object and free it when the count reached zero, and that approach has a problem. If two objects point at each other and nothing else points at them, the count never reaches zero and they are never freed. The tracing collector does not have that problem, because neither of them is reachable from the roots.
The second one is that you cannot ask the collector to collect a particular object, and you cannot ask it to run at a particular time. All you can do is ask it to try, through the method System.gc, and even that is only a suggestion.
The next question in this topic looks at how to watch what the collector is doing.