Java Reference
In-Depth Information
This program does nothing, but it illustrates the anatomy of a memory leak
for programs that use reference counting for garbage collection. Many pro-
grammers believe that circular references can lead to memory leaks in Java,
but Java garbage collectors no longer use reference counting. (Some C++
frameworks do still use reference counting for garbage collection, which
might account for some of the confusion on the subject.)
6.1.4
Reachable objects
Java garbage collectors use another technique, called reachable objects , to
determine whether an object is in use. The garbage collector periodically trav-
els the directed graph of allocated objects, attempting to visit every node by
following valid references. If an object can be reached, it is marked, and the
rest are freed. With this two-pass approach, sometimes called a mark-and-
sweep algorithm, circular references are handled appropriately: They are freed
only if they aren't reachable, effectively handling the problems shown in
figure 6.2 and listing 6.1.
root
D is needed to
be reachable.
Removing
F's refs will
make F
unreachable.
Removing D's
refs will make
E unreachable.
Figure 6.2 Java performs garbage collection by determining whether a node is reachable. An
object cannot be garbage-collected if it is reachable. You can break reachability (D, F) by
dereferencing an object or an object in the reference chain until it is no longer reachable (E).
Search WWH ::




Custom Search