Java Reference
In-Depth Information
Collection classes are frequently the source of memory leaks in Java: an application puts objects
into (for example) a HashMap object and never removes them. Over time, the hashmap grows ever
larger, consuming the heap.
One way developers like to handle this situation is with a collection class that holds indefinite ref-
erences. The JDK provides two such classes: WeakHashMap and WeakIdentityMap . Custom col-
lection classes based on soft (and other) references are available from many third-party sources
(including sample implementations of JSR 166, such as the one used for the examples of how to
create and store canonical objects).
Using these classes is convenient, but be aware that they have two costs. First, as discussed
throughout this section, indefinite references can have a negative effect on the garbage collector.
Second, the class itself must periodically perform an operation to clear all the unreferenced data
in the collection (i.e., that class is responsible for processing the reference queue of the indefinite
references it stores).
The WeakHashMap , class, for instance, uses weak references for its keys. When the weakly refer-
enced key is no longer available, the WeakHashMap code must clear out the value in the map that
used to be associated with that key. That operation is carried out every time the map is referenced:
the reference queue for the weak key is processed, and the value associated with any key on the
reference queue is removed from the map.
There are two performance implications to that. The first is that the weak reference and its associ-
ated value won't actually be freed until the map is used again. So if the map is used infrequently,
it means that the memory associated with the map won't be freed as quickly as desired.
Second, it means that the performance of operations on the map are unpredictable. Normally, op-
erations on a hashmap are quite fast; that's why the hashmap is so popular. The operation on a
WeakHashMap immediately after a GC will have to process the reference queue; that operation no
longer has a fixed, short time. So even if the keys are freed somewhat infrequently, performance
will be difficult to predict. Worse, if the keys in the map are freed quite frequently, the perform-
ance of the WeakHashMap can be quite bad.
Collections based on indefinite references can be useful, but they should be approached with cau-
tion. If it is feasible, have the application manage the collection itself.
Finalizers and final references
Every Java class has a finalize() method inherited from the Object class; that method can
used to clean up data once the object is eligible for GC. That sounds like a nice feature, and it
Search WWH ::

Custom Search