Singleton
Small review on singletons.
Singletons with needles and thread:
Unfortunately, in the example above, a thread may at any time pre-empt the call to getInstance(). For example, a thread may pre-empt a running thread at instance = new Singleton. If that were to happen, multiple Singleton instances might instantiate, thus defeating the purpose of a singleton.
To make a singleton thread safe, you have two choices. The first simply synchronizes the getInstance() method:
Synchronizing the method guarantees that a call to the method cannot be interrupted.
The second approach to thread safety declares a constant Singleton attribute on the Singleton class itself:
instance will initialize when the class loades. Both solutions guarantee only one Singleton will exist.
"
Singletons with needles and thread:
public class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if( instance == null ) {
instance = new Singleton();
}
return instance;
}
private Singleton() {}
public static void main( String [] args ) {
Singleton instance = Singleton.getInstance();
// ... manipulate instance
}
}
Unfortunately, in the example above, a thread may at any time pre-empt the call to getInstance(). For example, a thread may pre-empt a running thread at instance = new Singleton. If that were to happen, multiple Singleton instances might instantiate, thus defeating the purpose of a singleton.
To make a singleton thread safe, you have two choices. The first simply synchronizes the getInstance() method:
public class Singleton {
private static Singleton instance;
public synchronized static Singleton getInstance() {
if( instance == null ) {
instance = new Singleton();
}
return instance;
}
private Singleton() {}
public static void main( String [] args ) {
Singleton instance = Singleton.getInstance();
// ...
}
}
Synchronizing the method guarantees that a call to the method cannot be interrupted.
The second approach to thread safety declares a constant Singleton attribute on the Singleton class itself:
public class Singleton {
public final static Singleton instance = new Singleton();
private Singleton() {}
public static void main( String [] args ) {
Singleton instance = Singleton.instance;
// ...
}
}
instance will initialize when the class loades. Both solutions guarantee only one Singleton will exist.
"
0 Comments:
Post a Comment
<< Home