What are the differences between Weak Reference, Soft Reference andPhantom Reference with appropriate example

Questions by Pavan Sangyam

Showing Answers 1 - 1 of 1 Answers

meeta

  • Mar 27th, 2007
 

A reference object encapsulates a reference to some other object so that the reference itself may be examined and manipulated like any other object. Three types of reference objects are provided, each weaker than the last: soft, weak, and phantom. Each type corresponds to a different level of reachability, as defined below. Soft references are for implementing memory-sensitive caches, weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed, and phantom references are for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

 

Soft reference objects, which are cleared at the discretion of the garbage collector in response to memory demand.

 

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed.

 

Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed.

 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.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions