基于AtomicReference的单例模式写法

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编写的单例模式

复制代码
 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
复制代码

 

posted @   秋水秋色  阅读(647)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示