Solution 4: Use collections with weak references
The Java 1.2+ specifications build in some collections that implement weaker
references. WeakHashMap is a class that implements a hash table with weak ref-
erences. Objects referenced solely from this hash table are weakly reachable.
This type of collection is ideal for the optional registration of objects, and for
applications where it's difficult to pair add / remove method calls managing the
items in the hash table.
Solution 5: Use finally
Even when the calls are placed appropriately, exceptions can prevent the
proper cleanup from ever occurring. Important cleanup should be placed in
finally blocks. The Java finally block is executed after all code in a method,
including exception management, is processed. finally will guarantee that a
necessary block of code is executed, and is especially useful for cleanup.
Shooting memory leaks
These antipatterns can be used to identify existing leaks through inspection,
but what techniques can help you troubleshoot applications with existing
memory leaks? C++ programmers use spectacularly cumbersome tools and
techniques to solve memory-related problems. For the most part, Java pro-
grammers prefer to stay above the fray. Sometimes, however, we aren't so for-
tunate. In this section, we'll look at the strategies that can help. The basic
steps to finding memory leaks are determining whether a problem exists, iso-
lating the problem, repairing the problem, and protecting against the problem
in the future.
Make sure there is a leak
Much is left to the discretion of garbage collectors. In some cases, garbage
collection can occur relatively frequently. In other cases, it may not run at all.
Many of the faster JVM s try to limit the number of times that garbage collec-
tion is run. Some JVM s execute garbage collection only when memory
resources are close to exhausted. In such cases, an application can appear to
leak. Watching available memory on a simple memory monitor is not enough.
A good strategy is to take memory snapshots before and after suggesting gar-
bage collection with a call to System.gc . (This method call should seldom or
never be used in production code.) Many tools can force garbage collection.
Tools are available to help you analyze memory leaks. A few are J-Insight
(from alphaWorks), J-Probe (from Sitraka Software), and OptimizeIt (from