Java Reference
In-Depth Information
6.8
Antipatterns in this chapter
These are the templates for the antipatterns that appear in this chapter. They
provide an excellent summary format and form the basis of the cross-refer-
ences in appendix A.
Lapsed Listeners
D ESCRIPTION : The Publish / Subscribe design pattern requires applications
or classes with an interest in an event to register. The Lapsed Listener is
one form of memory leak where an event listener is registered without
being removed. If the life cycle of the listener registry is long, then a
memory leak will occur.
R ELATED ANTIPATTERNS : The Leak Collection. The Lapsed Listener is a
special case of the more general Leak Collection.
M OST FREQUENT SCALE : Application.
R EFACTORED SOLUTION NAME : Weak References, or Pairing Register
with Remove.
R EFACTORED SOLUTION TYPE : Software.
R EFACTORED SOLUTION DESCRIPTION : One solution to this problem is
to explicitly remove the listener. For clarity, register and remove listeners
in add / remove pairs. If this cannot be done in the same method, the two
methods should be in close proximity. Another solution is to weaken the
reference with Java weak reference objects.
T YPICAL CAUSES : Programming hygiene is a common cause. When regis-
trations are not placed in close proximity to removes, it is easy to neglect
the remove, because the symptoms are delayed.
A NECDOTAL EVIDENCE : “I didn't know you could have a memory leak in
Java.” “The system gets slower and slower, and then it hangs or traps.”
S YMPTOMS , CONSEQUENCES : Some objects are not garbage collected,
even though their primary user is. This leak will cause the system to slow
over its life cycle, until it's terminated or eventually dies.
S OLUTION ALTERNATIVES : Remove the reference appropriately or
shorten the life cycle of the registry. Adding a listener without a weak ref-
erence or a corresponding remove is possible if the life cycle of the registry
is short, but this is vulnerable to changes in life cycle and cut and paste.
Search WWH ::




Custom Search