Rouki
Rouki

Reputation: 2345

Garbage collector - more than one pointer to the same object

I have a question about the garbage collector implementation in Java.

Say I do:

Person p1 = new Person();
Person p2 = p1;

I can imagine how the garbage collector knows to deallocate the person object when p1 refers to null but I don't get how does he collect the information that there's now ANOTHER pointer to the same object named P2?

When I use the "new" operator it makes sense since it calls the person and Object ctor to initialize that object and in the way it can also save the ptr's address so it can know when it refers to null. But how can it know that a stack allocated pointer (like the "p2") also refers to that object so it knows that it shouldn't deallocate it when p1 refers to null?

Upvotes: 0

Views: 90

Answers (2)

Stephen C
Stephen C

Reputation: 718798

There are whole textbooks on how garbage collectors work. And different ones work in different ways.

But yes, the garbage collector does (in a sense) know where all of the pointers are.

However perhaps the source of your confusion is that you think that objects get garbage collected immediately when nothing refers to them. This is not true for typical garbage collectors. So that means that the GC doesn't need to know about all of the pointers all of the time.

In fact, the GC normally only runs "once in a while". And what it does in simple terms1 is to trace through all of the places that the program refers to objects (directly or indirectly) to figure out which ones are not garbage. The rest (the ones the GC didn't trace) are garbage.

1 - Actually, this is a significant over-simplification. But if you want the full story, you will need to read a more comprehensive resource ... or a text book.

Upvotes: 1

nullptr
nullptr

Reputation: 11058

Since the garbage collector is a part of the language, it can track all pointers of a program or enumerate them all at some moment. It's provided by language itself: the Java language is designed in such way that it's possible to create a Java virtual machine which keeps track of all existing pointers and can reliably distinguish a pointer from any other data.

Upvotes: 3

Related Questions