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;
System.gc();
}
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();
d_.addPropertyChangeListener(this);
}
o
This reference will prevent
garbage collection.
o
public void propertyChange(PropertyChangeEvent evt){}
}
class D
{
private static D singleton_ = null;
private PropertyChangeSupport listeners_ =
new PropertyChangeSupport(this);
Static instance
variable; getInstance
method. Singleton!
o
private D(){}
public static D getInstance()
{
if (singleton_ == null)
singleton_ = new D();
return singleton_;
}
Method registers the
event (but there is no
remove). Singleton!
o
public void addPropertyChangeListener(
PropertyChangeListener listener)
{
listeners_.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(
Search WWH ::




Custom Search