In Java the memory allocated by NIO direct buffers is freed with sun.misc.Cleaner
instances, some special phantom references that are more efficient than object fin
After spending more time reading the API doc ( http://docs.oracle.com/javase/7/docs/api/java/lang/ref/package-summary.html ) I think I have a more detailed answer:
1) it is possible to reuse sun.misc.Cleaner to perform the efficient cleanup of your own custom classes. You declare the cleaner by calling the provided factory method:
sun.misc.Cleaner.create(Object ob, Runnable cleanup);
For some time I could not get it to work properly, that's because I was moronic enough to define the runnable cleanup code of my cleaner as an anonymous class, that kept a (strong) reference to my referent object, preventing it from ever being "phantom reachable"...
2) There is no other way to implement such efficient cleanup (not even with the help of phantom references)
Indeed the reference handler thread handles instances of sun.misc.Cleaner in a special way:
// Fast path for cleaners
if (r instanceof Cleaner) {
((Cleaner)r).clean();
continue;
}
That means that the cleanup code is called directly from the reference handler thread, while in standard usage, the references must be enqueued by the reference handler thread and then dequeued and processed by another application thread.