My question that sums it all up:
- Can a strongly reachable Java PhantomReference stop its referent object's memory from being reclaimed by the Garbage Collector (GC)?
Details follow:
Callum posted this question as well but it is not answered straightforwardly. One response there refers to an article by Ethan Nicholas which seems to answer my question with a "No" but I'm not sure that is correct.
Based on my reading of the Java API I would have to answer my question with "Yes":
- As long as PhantomReference.clear() is not called, and the PhantomReference instance itself is still strongly referred to, the referent object's memory will never be reclaimed and the referent will remain in a phantom reachable state.
To support this understanding I will quote the Java Docs:
- "Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable."
For example, let's say I make a phantom reference and keep that instance in a List of PhantomReference. Then its referent falls from strongly reachable to phantom reachable.
If you take a look at com.google.common.base.internal.Finalizer.java, you will see the following code:
private void cleanUp(Reference reference) throws ShutDown { ... /* * This is for the benefit of phantom references. Weak and soft * references will have already been cleared by this point. */ reference.clear(); ... }
I would prefer someone who is experienced with the subject to respond rather than doing a web search and providing me with links. Thanks!