Java Reference
In-Depth Information
17.5.4. Finalization and Reachability
An object becomes finalizable when it becomes weakly reachable (or
less). It would seem that to determine reachability you need simply ex-
amine the source code for your applications. Unfortunately, such an ex-
amination would often be wrong. Reachability is not determined by the
statements in your source code, but by the actual state of the virtual
machine at runtime. The virtual machine can perform certain optimiza-
tions that make an object unreachable much sooner than a simple ex-
amination of the source code would indicate.
For example, suppose a method creates an object that controls an ex-
ternal resource and that the only reference is through a local variable.
The method then uses the external resource and finally nulls the local
reference or simply returns, allowing the object to be finalized and re-
lease the external resource. The programmer might assume that the
object is reachable until that reference is set to null or the method re-
turns. But the virtual machine can detect that the object is not referen-
ced within the method and may deem it unreachable and finalizable the
instant after it was constructed, causing immediate finalization and re-
lease of the resource, which was not something the programmer inten-
ded. Even the reference queue designs that we have discussed depend
on the referent remaining reachable as long as the programmer expects
it to be reachable.
The optimizations under consideration only apply to references held on
the stackthat is, references stored in local variables or parameters. If a
reference is stored in a field, then the object remains reachable at least
until the field no longer refers to it. This approach also covers the case
of inner class objectsan inner class instance is reachable whenever its
enclosing instance is reachable.
There are further subtle interactions between finalization, synchroniza-
tion, and the memory model, but these are advanced topics unneeded
by most programmers and are beyond the scope of this topic.
Don't ever take a fence down until you know the reason why it was
put up.
 
Search WWH ::




Custom Search