Java Reference
In-Depth Information
need to use the singleton get an instance. Consider the program shown in
listing 6.3, which was taken from “Plugging Memory Leaks,” by Tony K.T.
Leung. (Some cosmetic changes have been made for easier annotation.)
Listing 6.3
Leaking memory through registering to a singleton
import java.beans.*;
public class Test
public static void main(String[] args)
C c = new C();
c = null;
o References C, removes
reference, and then
runs gc , suggesting
garbage collection.
class C implements PropertyChangeListener
private D d_ = null;
A singleton, with a
different life cycle from C.
public C ()
d_ = D.getInstance();
This reference will prevent
garbage collection.
public void propertyChange(PropertyChangeEvent evt){}
class D
private static D singleton_ = null;
private PropertyChangeSupport listeners_ =
new PropertyChangeSupport(this);
Static instance
variable; getInstance
method. Singleton!
private D(){}
public static D getInstance()
if (singleton_ == null)
singleton_ = new D();
return singleton_;
Method registers the
event (but there is no
remove). Singleton!
public void addPropertyChangeListener(
PropertyChangeListener listener)
public void removePropertyChangeListener(
Search WWH ::

Custom Search