weak vs phantom references
per.liden at oracle.com
Sat Nov 3 18:13:05 UTC 2018
On 2018-11-03 09:58, Michał Zegan wrote:
> I am asking only for educational purposes.
> Yes, i sort of remember that PhantomReferences were not cleared when
> enqueued contrary to all other ones before, but now they are.
> So if, as said, finalization didn't exist, then for me enqueuing a weak
> reference seems the same as enqueuing a phantom one, because in both
> cases they are cleared, and in both cases you cannot access their
> referents. And such an object would probably also be eligible for
Yes, if the concept of finalization didn't exist, then weakly reachable
and phantom reachable would be the same thing, and there would be no
need to separate the two.
> W dniu 03.11.2018 o 02:01, Mandy Chung pisze:
>> On 11/2/18 4:15 PM, Michał Zegan wrote:
>>> 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
>> 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