Java Reference
In-Depth Information
private MySingleton() {}
public static MySingleton getInstance() {
return instance;
}
}
Double‐checked locking is another highly popular mechanism to create singletons. It is considered
more secure than other methods because it checks the instance of the singleton once before locking
on the singleton class and again before the creation of the object. Listing 4‐5 shows this method.
LISTING 4‐5: Implementing the double‐checked locking
package com.devchronicles.singleton;
public class MySingleton {
private volatile MySingleton instance;
private MySingleton() {}
public MySingleton getInstance() {
if (instance == null) { // 1
synchronized (MySingleton.class) {
if (instance == null) { // 2
instance = new MySingleton();
}
}
}
return instance;
}
}
The getInstance() method checks the private MySingleton instance member twice (once at comment
1 and then again at comment 2) for being null before creating and assigning a MySingleton instance.
However, none of those approaches is 100 percent safe. For example, the Java Rel ection API allows
developers to change the access modii er of the constructor to Public, thus exposing the singleton to
the possibility of re‐creation.
The best way to create singletons in Java is by using the enum type, which was introduced in Java 5
and is shown in Listing 4‐6. This approach is also heavily advocated by Joshua Bloch in his book
Effective Java . 3 Enum types are singletons by nature, so JVM handles most of the work required to
create a singleton. Thus, by using an enum type, you free yourself from the task of synchronizing
object creation and provision and avoid problems associated with initialization.
LISTING 4‐6: Enum type implementation of the singleton pattern
package com.devchronicles.singleton;
public enum MySingletonEnum {
INSTANCE;
public void doSomethingInteresting(){}
}
Search WWH ::




Custom Search