使用CAS实现单例模式

562 阅读1分钟

主要记录一下一种比较少见的实现单例模式的方法。

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

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

测试一下:

public static void main(String[] args) throws InterruptedException {
    AtomicReference<SingleInstance> instance1 = new AtomicReference<>();
    AtomicReference<SingleInstance> instance2 = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(2);
    new Thread(()->{
        instance1.set(SingleInstance.getInstance());
        latch.countDown();
    }).start();
    new Thread(()->{
        instance2.set(SingleInstance.getInstance());
        latch.countDown();
    }).start();
    latch.await();
    System.out.println(instance1.get() == instance2.get());
}

使用CAS的主要一个优点就是没有线程切换和阻塞带来的开销,缺点也很明显,就是对cpu资源的消耗比较大。