Search code examples
javafinalizephantom-reference

Phantom Referenced Objects


Phantom References serve for post-mortem operations. The Java specification states that a phantom referenced object will not be deallocated until the phantom-reference itself is cleaned.

My question is: What purpose does this feature (object not deallocated) serve?

(The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).


Solution

  • The only good use-case I can think of, that would prevent deallocation, is one where some kind of JNI-implemented asynchronous data source is writing into the referenced object, and must be told to stand down - to stop writing into the object - before the memory is recycled. If prior deallocation were allowed, a simple forgot-to-dispose() bug could result in memory corruption.

    This is one of the cases where finalize() would have been used in the past, and probably drove some of its quirks.