If an object has 5 references can that object find out what is referenced to him?
Because I know that Java (and hopefully C#) have a list of that for the GC.
If an object has 5 references can that object find out what is referenced
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, there’s no “list of references”. The GC doesn’t need to know everything that references an object – it just needs to know if anything references an object.
As a very crude model of what the GC does, it marks every object in the heap as garbage, then looks at objects which it knows to be non-garbage (“root” objects). For example, it will look at the stack of each thread and for each instance method in the thread, it will usually1 mark the target instance as non-garbage.
Then it will go through each of those roots, and see what objects those ones refer to… and mark them as non-garbage. It will recurse down, finding everything it can. Whatever hasn’t been marked as non-garbage can then be collected (or finalized).
As you can see from this algorithm, the GC doesn’t need to keep a full list of references for each object – just a bit to say “garbage” or “non-garbage”.
Obviously in reality the GC is much more complicated than this, in both Java and .NET, with generational garbage collectors and various strategies to minimise the GC “pause” and use multiple threads for GC. Hopefully this simplified view is enough to explain why even the GC doesn’t have a list of references though.
1 Not always, in the case of .NET. An object can be garbage collected while an instance method is still running “in” it, if that method doesn’t refer to any fields in the object from the current point onwards.