是否使用AtomicReference正确实现了延迟初始化单例?如果不是 - 可能的问题是什么?
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicReference;
public class Singleton implements Serializable {
private static final Singleton _instance = new Singleton();
private static AtomicReference<Singleton> instance = new AtomicReference<Singleton>();
private Singleton() {
}
public static Singleton getInstance() {
if (instance.compareAndSet(null, _instance)) {
synchronized (_instance) {
_instance.init();
instance.set(_instance);
}
}
return instance.get();
}
private void init() {
// do initialization
}
private Object readResolve() throws ObjectStreamException {
return getInstance();
}
}
Run Code Online (Sandbox Code Playgroud)
Sea*_*oyd 10
不,这很糟糕:
public static Singleton getInstance() {
// new "singleton" for every method call
Singleton s = new Singleton();
^^^^^^^^^^^^^^
if (instance.compareAndSet(null, s)) {
synchronized (s) {
s.init();
}
}
return instance.get();
}
Run Code Online (Sandbox Code Playgroud)
使用AtomicReference是一个不错的主意,但它不起作用,因为Java没有懒惰的评估.
经典的1.5单例方法是:
渴望单身人士:
public final class Singleton{
private Singleton(){}
private static final Singleton INSTANCE = new Singleton();
public Singleton getInstance(){return INSTANCE;}
}
Run Code Online (Sandbox Code Playgroud)
懒惰单身人士,内部持有人类:
public final class Singleton{
private Singleton(){}
private static class Holder{
private static final Singleton INSTANCE = new Singleton();
}
public Singleton getInstance(){return Holder.INSTANCE;}
}
Run Code Online (Sandbox Code Playgroud)
Enum Singleton:
public enum Singleton{
INSTANCE;
}
Run Code Online (Sandbox Code Playgroud)
你应该坚持使用其中一个
| 归档时间: |
|
| 查看次数: |
6160 次 |
| 最近记录: |