基于AtomicReference的单例模式写法

时间:2022-05-24 17:42:54

AtomicReference类主要属性(来源于jdk1.7中的源码)

public class AtomicReference<V> implements java.io.Serializable {
    private static final long serialVersionUID = -1848883965231344442L;

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicReference.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile V value;
    .......

}

 

采用AtomicRerence编写的单例模式

基于AtomicReference的单例模式写法基于AtomicReference的单例模式写法
 1 public class Singleton {
 2     
 3     private static AtomicReference<Singleton> singleton = new AtomicReference<Singleton>();
 4     
 5     private Singleton(){}
 6     
 7     public static Singleton getInstance() {
 8         
 9         for(;;) {
10             Singleton instance = singleton.get();
11             if(instance != null ) {
12                 return instance;
13             }
14             instance = new Singleton();
15             if(singleton.compareAndSet(null, instance)) {
16                 return instance;
17             }
18         }
19     }
20     
21 }
View Code