开发者

who knows me? (Chronicles of an object)

开发者 https://www.devze.com 2023-01-05 00:17 出处:网络
If an object has 5 references can that object find out what is r开发者_如何学Goeferenced to him?

If an object has 5 references can that object find out what is r开发者_如何学Goeferenced to him? Because I know that Java (and hopefully C#) have a list of that for the GC.


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.


If you fail to find language support for this, simply have each object that wants to hold a reference to the object in question call a method that tells the object in question that it is being referenced. This object would then add the referring object to a list. Whenever you give up your reference to that object, you call another method that would remove the referrer from the list.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号