Example:
public void foo() {
A a = new A();
}
What if there is this sequence of events?
A()
constructor runs. Now there is an instance in the heap.a
.How does it prevent this from occurring? I would greatly appreciate links to article where it is explained.
This is easy to answer once you know that the call stack is traversed by the garbage collector (GC). So when it traverses the stack of the method foo
, it simply knows that there are references (a
) pointing to that heap memory.
In order to know what is garbage, the GC has to first scan everything that is alive. Since there are references pointing to that memory (the new A()
); that is treated alive, at least until a
is used, somewhere, by some thread.