I haven't used PhantomReferences. There seems to be very few good examples of real-world use.
When a phantom shows up in your queue, how do you know which object it is/was? The get() method appears to be useless. According to the JavaDoc,
Because the referent of a phantom reference is always inaccessible, this method always returns null.
I think that unless your object is a singleton, you always want to use a subclass of PhantomReference, in which you place whatever mementos you need in order to understand what died.
Is this correct, or did I miss something?
Is this also true for SoftReferences? For WeakReferences?
Links to relevant examples of usage would be great.
You could also use a
Map<Reference<?>, SomeMetadataClassOrInterface>
to recover whatever metadata you need. SinceReferenceQueue<T>
returns aReference<T>
, you either have to cast it to whatever subclass ofPhantomReference
you expect, or let aMap<>
do it for you.For what it's worth, it looks like using PhantomReferences puts some burden on you:
so you'd have to
clear()
the references yourself in order for memory to be reclaimed. (why there is usefulness in having to do so vs. letting the JVM do this for you is beyond me)