Another good article on the topic:
Java Reference Objects or How I Learned to Stop Worrying and Love OutOfMemoryError, with nice diagrams
Extract:
As you might guess, adding three new optional states to the object life-cycle diagram makes for a mess.
Although the documentation indicates a logical progression from strongly reachable through soft, weak, and phantom, to reclaimed, the actual progression depends on what reference objects your program creates.
If you create a WeakReference
but don't create a SoftReference
, then an object progresses directly from strongly-reachable to weakly-reachable to finalized to collected. object life-cycle, with reference objects
It's also important to remember that not all objects are attached to reference objects — in fact, very few of them should be.
A reference object is a layer of indirection: you go through the reference object to reach the referred object, and clearly you don't want that layer of indirection throughout your code.
Most programs, in fact, will use reference objects to access a relatively small number of the objects that the program creates.
References and Referents
A reference object provides a layer of indirection between your program code and some other object, called the referent.
Each reference object is constructed around its referent, and provides a get() method to access the referent. Once you create a reference, you cannot change its referent. Once the referent has been collected, the get() method returns null. relationships between application code, soft/weak reference, and referent
Even more examples: Java Programming: References' Package
Case 1: This is the regular case where Object is said to be strongly reachable.
Case 2: There are two paths to Object, so the strongest one is chosen, which is the one with the strong reference hence the object is strongly reachable.
Case 3: Once again there are two paths to the Object, the strongest one is the Weak Reference (since the other one is a Phantom Reference), so the object is said to be weakly reachable.
Case 4: There is only one path and the weakest link is a weak reference, so the object is weakly reachable.
Case 5: Only one path and the weakest link is the phantom reference hence the object is phantomly reachable.
Case 6: There are now two paths and the strongest path is the one with a soft reference, so the object is now said to be softly reachable.