Java Reference
In-Depth Information
listener that's added. On the other hand, weak references do add to our bag of
tricks for memory management. Table 6.2 shows the strengths and weak-
nesses of each solution.
Table 6.2 These are the solutions to the Lapsed Listener antipattern. Each circumstance is
unique, and each solution has pros and cons that must be considered.
Balancing removes and adds
The design is clean, readable,
and intuitive. Implementing
graphical components is
The placement of the remove is
not always intuitive, especially
for objects that are not compo-
Shorten the anchor's life cycle
The solution can be very easy
to implement and is easy to
The solution is vulnerable to
bugs, resulting in memory
Weak references
This is the most generic solu-
tion, and is also very easy to
The code for weak references
is not as intuitive and readable
as direct references.
Antipattern: The Leak Collection
The root of the Lapsed Listener antipattern is a collection with a long life
cycle that has object references inserted but not removed. The references pro-
hibit effective garbage collection because they make the referenced object
reachable. The Leak Collection is a general case of the Lapsed Listener anti-
pattern. Whenever we have a collection with a long life cycle that has the
potential to contain objects that aren't removed, we have the possibility of a
memory leak. Figure 6.4 shows the basic antipattern.
In essence, an application (A) allocates an object (B) with a short life cycle,
registers the object in a collection (C) having a relatively long life cycle, and
then removes the reference to object B. If the collection has a long life cycle—
as many shared collections do—and if the object isn't removed from the col-
lection before the reference is garbage collected, we'll have a memory leak.
Many different design patterns and problem domains call for singleton col-
lections. Here are a few:
Caches: A singleton hash table is the implementation of choice for a
cache. When a cache doesn't have a policy to expire old entries, we have
the potential for a leak.
Search WWH ::

Custom Search