A summarized notes on less known Java garbage collection and the different types of references in Java.
There are four types of references in Java, in order of their “strong-ness”: strong, soft, weak, phantom. Strong references are all the normal references you see in code all the time. All the others are from java.lang.ref.* and require extra code.
Reachability
An object is
- strongly reachable if at least one of the chain of references is all strong reference
- weakly reachable if it is not strongly reachable but is reachable through a chain with at least one weak reference
- softly reachable if it is not strongly or softly reachable, but is reachable through a chain with at least one soft reference
- phantomly reachable if the object cannot be reached through the above chains, but can through a chain with at least one phantom reference
- unreachable otherwise
Garbage Collection
- GC will not claim any object that is strongly reachable
- GC will claim at its discretion any object that is softly reachable, but generally this is done only when its running out of resources. This means that softly reachable objects may stay in memory for a while
- GC will reclaim an object that only has weak reference left
- Phantom reachable objects have been garbage collected (finalized). This is the only way to know when an object has been freed by GC
More on Phantom references
Generally, an object is not guaranteed to be gc-ed when finalize is called, for an resurrection example, refer to this
The only way to be sure that an object has been reclaimed is through the use of Phantom references and a reference queue. See here