Java Reference
In-Depth Information
•
An object is
strongly reachable
if it can be reached through at
least one chain of strong references (the normal kind of referen-
ces).
•
An object is
softly reachable
if it is not strongly reachable, but is
reachable through at least one chain containing a soft reference.
•
An object is
weakly reachable
if it is not softly reachable, but is
reachable through at least one chain containing a weak referen-
ce.
•
An object is
phantom reachable
when it is not weakly reachable,
has been finalized (if necessary), but is reachable through at least
one chain containing a phantom reference.
•
Finally, an object is
unreachable
if it is not reachable through any
chain.
Once an object becomes weakly reachable (or less), it can be finalized.
If after finalization the object is unreachable, it can be reclaimed.
Objects need not actually go through all these stages. For example, an
object that is reachable only through strong references becomes un-
reachable when it is no longer strongly reachable.
The reachability stages of an object trigger behavior in the garbage col-
lector appropriate to the corresponding reference object types:
•
A softly reachable object may be reclaimed at the discretion of
the garbage collector. If memory is low, the collector may clear a
SoftReference
object so that its referent can be reclaimed. There
are no specific rules for the order in which this is done (but a good
implementation will prefer keeping recently used or created refer-
ences, where "used" is defined as "invoked
get
"). You can be sure
that all
SoftReference
s to softly reachable objects will be cleared
before an
OutOfMemoryError
is thrown.
•
A weakly reachable object will be reclaimed by the garbage col-
lector. When the garbage collector determines that an object is