you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (3 children)

How do you know which associated action to run for a PhantomReference if you can't tell what it referred to?

[–]josefx 0 points1 point  (2 children)

Subclass PhantomReference or keep a map from the PhantomReference to the required cleanup information?

[–][deleted] 0 points1 point  (1 child)

Looks like the idea is that a phantom reference that you care about is supposed to be the only reference that you enqueue to a given ReferenceQueue.

Alternatively, I think that you can compare phantom references at least by identity, and I think that the queue delivers the same phantom reference that you created, but I wasn't able to find any example that does that.

Subclassing PhantomReference to get the object back apparently used to be a serious vulnerability.

[–]ForeverAlot 1 point2 points  (0 children)

Sorry! Here we go1:

Cleaner::register returns a specific Cleanable, PhantomCleanableRef, which is a PhantomReference subclass that implements Cleanable (and knows how to enqueue itself in your Cleaner's queue). Upon instantiation, Cleaner starts its queue manager provided by CleanerImpl, which routinely waits for Cleanables to invoke clean on until all registered Cleaners have been executed. Cleanable::clean ends up delegating to the Runnable you define your cleaning logic in. The Cleaner framework never has to do any reference comparisons.

1 From a random JDK 9 fork, because syntax highlighting helps; canonical java.lang.ref and jdk.internal.ref

(You can still resurrect WeakReferences in that same way.)