Java Reference
In-Depth Information
make object E unreachable, and will be collected on the next garbage-
collection pass.
Eventually, chains are garbage-collected as they fall out of use. However, if
object B or C has a long life cycle, then objects D and E will remain reach-
able unless the references to D are explicitly broken. If the programmer no
longer intends to use D and E, we have a classic Java memory leak. Most of
the memory leaks in this chapter will deal with some type of anchor with a
very long life cycle that references unused objects, such as collections, sin-
gletons, and listeners. If nothing is done to remove the reference, we'll have
a memory leak.
Finding Java leaks
Java leaks can be especially difficult to find. For the most part, Java applica-
tions are at a higher level than C++ applications. We Java programmers are not
well versed with the low-level tools and techniques that complex memory
problems demand. Factors that contribute to the dilemma of finding and
troubleshooting memory leaks in Java include:
Simply watching memory by using a monitor, like the Windows Task Man-
ager, is not sufficient. Garbage-collection scheduling varies, and memory
is not freed until garbage collection is scheduled.
Under certain circumstances, the Java garbage collector is not executed at
all. Some garbage collectors are activated only when memory use
reaches a certain threshold. In those instances, if tests do not model
real-world usage scenarios closely, you could easily miss memory leaks
or incorrectly assume leaks exist.
References are in clusters, so the impact of leaks is greater. In Java, each
block of memory is not explicitly freed. If you forget to remove a critical
reference to a single object, it may reference many other objects. A Java
interface developed with the Swing component library can have refer-
ences to dozens or even hundreds of child classes. Further, since the
classes also have back pointers, references to a child class can make an
entire user interface tree reachable.
More than one reference might be causing the leak. Because all references
must be broken to make a class unreachable and eligible for garbage col-
lection, breaking a single reference might not be enough. A correct fix
may not have the desired impact if multiple bugs exist.
Search WWH ::

Custom Search