java – 使用AtomicReference的Singleton

前端之家收集整理的这篇文章主要介绍了java – 使用AtomicReference的Singleton前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否使用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();
    }

}

解决方法

不,这很糟糕:
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();
}

使用AtomicReference是一个不错的主意,但它不起作用,因为Java没有懒惰的评估.

经典的1.5单例方法是:

渴望单身人士:

public final class Singleton{
    private Singleton(){}
    private static final Singleton INSTANCE = new Singleton();
    public Singleton getInstance(){return INSTANCE;}
}

懒惰单身人士,内部持有人类:

public final class Singleton{
    private Singleton(){}
    private static class Holder{
        private static final Singleton INSTANCE = new Singleton();
    }
    public Singleton getInstance(){return Holder.INSTANCE;}
}

Enum Singleton:

public enum Singleton{
    INSTANCE;
}

你应该坚持使用其中一个

原文链接:/java/121706.html

猜你在找的Java相关文章