使用CAS(AtomicReference)实现的单例模式

CAS是项乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。

乐观锁的一种实现方式——CAS

在JDK1.5 中新增java.util.concurrent(J.U.C)就是建立在CAS之上的。相对于对于synchronized这种阻塞算法,CAS是非阻塞算法的一种常见实现。所以J.U.C在性能上有了很大的提升。

借助CAS(AtomicReference)实现单例模式:

public final class SingleInstance {
    private static final AtomicReference instanceRef = new AtomicReference<>();

    private SingleInstance() {
    }

    public static SingleInstance getInstance() {
        for (; ; ) {
            SingleInstance instance = instanceRef.get();
            if (instance != null) {
                return instance;
            }
            instanceRef.compareAndSet(null, new SingleInstance());
        }
    }

}

与sychronized实现的单例相比

优点:

  1. 无锁

缺点:

  1. 对象可能会被创建多个,设置失败的会被舍弃
  2. 代码相对稍微复杂

参考文章:

  • https://www.cnblogs.com/snow-man/p/9970523.html 修正了文章中的错误

你可能感兴趣的:(使用CAS(AtomicReference)实现的单例模式)