Java Reference
In-Depth Information
The symptoms are not as dramatic or immediate as those in C ++ . In C++,
a reference is not correctly updated, the result is often a crash due to a
dangling pointer. In Java, the symptoms are not immediate, so generat-
ing failure test cases is not as easy.
This chapter will help you recognize some common types of memory leaks
before they become problems. Coding conventions make it easier for you to
account for key references that must be explicitly removed to achieve effective
memory management. Now that we've reviewed memory management and
seen some basic patterns that could lead to Java memory leaks, let's examine
some specific antipatterns.
6.3
Antipattern: Lapsed Listeners Leak
The Lapsed Listener Leak is a common antipattern given its name by Ethan
Henry and Ed Lycklama in an article titled “How Do You Plug Java Memory
Leaks?” One design pattern with the potential for memory leaks is the Event
Listener design pattern, which is used to establish interest in an event without
forcing broadcast messaging. Objects request notification of an event by regis-
tering a listener or method that will be called if the event occurs. Java uses this
design pattern in several places; three are interesting for the purposes of this
antipattern. First, the Java user interface framework (called the AWT library)
uses this design pattern for notification of actions. Second, generic JavaBeans
can use an interface called PropertyChangeListener to establish notification for
a changing property. Third, the Java Swing component library uses the Model-
View-Controller design pattern. The model is registered with a user interface
component, and the user interface is notified when the model changes.
Three factors make event-notification design patterns ripe for memory leaks:
The event registry can be a collection with a long life cycle. A user inter-
face component that is registered cannot be garbage collected until it is
removed or the root registry object (or anchor ) is garbage collected. If
the anchor has a long life cycle, garbage collection may not occur at all.
The symptoms for failing to remove the notification are initially
benign. The benign symptoms make it easy for the leak to get through
initial tests.
Many visual programming frameworks, Swing programming samples,
and wizards do not remove listeners. Whether these samples are created
with a development environment or through cut and paste, memory
leaks are not expected from these sources.
Search WWH ::




Custom Search