Mukul Goel Mukul Goel - 1 year ago 171
Java Question

What is phantom reference in java

There are four type of references in Java: Strong, Soft, Weak, and phantom. Kindly elaborate where and how Java exactly use phantom reference.


I did read the javaDoc, as assylias posted below. the section says an object is phantom rechable if it has been finalized and some phantom refernce refers to it. I dint quite get that statement.

What is the use of phantom and in which cases shall we use it?

Answer Source

How each type of reference works is described in the java.lang.ref package javadoc:

Going from strongest to weakest, the different levels of reachability reflect the life cycle of an object. They are operationally defined as follows:

  • An object is strongly reachable if it can be reached by some thread without traversing any reference objects. A newly-created object is strongly reachable by the thread that created it.
  • An object is softly reachable if it is not strongly reachable but can be reached by traversing a soft reference.
  • An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization.
  • An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it.
  • Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways.

There are a few posts on Stack OVerflow that give examples of how and when you might need a PhantomReference:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download