Hope you don’t mind, I may be missing something; I just need some clarification for the following scenario: If an object a contains a reference to a static list and also an entry in that static list, and object a falls out of scope, will it be garbage collected? Do I need to set object a’s reference to the static list and reference to the entry in that list to null before it becomes eligible?
I understand that the static list contains objects which will live for the lifetime of the application, so I was thinking since object a still references an entry in that static list, it is still in the main dependency object graph of objects which are still live?
Thanks in advance
Firstly, objects don’t fall out of scope, variables do. The difference is one of semantics most of the time, but vital here.
Let’s create a concrete example of what you talk about:
As seen here, scope is nothing, reachability is everything.
In the case of an object that refers to a static, what it refers to is irrelevant, only what refers to it.
In particular, note that this means that circular references do not prevent items from being collected, unlike with some reference-counted garbage collection approaches.