weak vs phantom references

Mandy Chung mandy.chung at oracle.com
Sat Nov 3 01:01:46 UTC 2018

On 11/2/18 4:15 PM, Michał Zegan wrote:
> Hello,
> Something that is not clear to me. If some object is referenced to by a
> weak reference, it means it is not yet finalized, in the case of objects
> being phantom reachable, they may be finalized but are still not garbage
> collected.

If an object is phantom reachable, it has been finalized.  In addition, 
when the referent of the phantom reference is cleared, the referent is 
eligible for reclaimed.
> My question is: if finalization wouldn't be used and you had a guarantee
> that it isn't used for the given object, could weak references be used
> in place of phantom references for cleanup purposes?
> I know that phantom references must be registered with a ref queue and
> you cannot get the referent using their get() method, but weak
> references can also be registered into a queue, and in any case, when
> any kind of reference lands in a queue, it is guaranteed that it is
> already cleared, so if you use weak references for cleanup by polling
> them from the queue, you also cannot access the referent.
> Not sure if I understand it right...

What kind of clean up are you thinking of?  FYI. java.lang.ref.Cleaner API
may be interesting to you which you don't need to maintain your reference queue.

One relevant spec change that may be relevant: JDK-8071507 changed the 
phantom reference be automatically-cleared reference as soft and weak 
reference do in JDK 9.   Prior to JDK 9, the referent of a phantom 
reference may be kept alive until the reference object is collected.  I 
do think if there were no finalizer at all, it would need two separate 
reachability states.


More information about the jdk-dev mailing list