这个Singleton是一个线程安全的吗?

Kut*_*ach 4 java concurrency singleton multithreading atomicity

基于这个主题,我提出了一个有趣的Singleton模式版本,该实现基于AtomicIntegers.

问题是:

  • 这个实现是正确的和线程安全的,通常可以使用Atomic Variables进行线程同步和管理吗?
  • 附加问题:如果这个实现是线程安全的,我真的需要一个volatile实例变量的修饰符吗?
public class StrangeSingleton
{

    private StrangeSingleton() {};

    private static volatile Object instance;

    private static AtomicInteger initCounter = new AtomicInteger();
    private static AtomicInteger readyCounter = new AtomicInteger();

    static Object getInstance()
    {

        if (initCounter.incrementAndGet() == 1)
        {
            instance = new Object();

            readyCounter.incrementAndGet();

            return instance;
        }
        else if (readyCounter.get() == 1)
        {
            return instance;
        }
        else
        {
            //initialization not complete yet.
            //write here some logic you want:               
            //sleep for 5s and try one more time,
            //or throw Exception, or return null..

            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:添加了私有构造函数,但它不是重点.

Pet*_*rey 8

这个实现是正确的和线程安全的,通常可以使用Atomic Variables进行线程同步和管理吗?

但它通常更加复杂和CPU密集,因为您需要忙着等待快速响应变化.

附加问题:如果这个实现是线程安全的,我真的需要一个volatile修饰符作为实例变量吗?

在这种情况下,您不会这样做,因为AtomicInteger包含易失性字段,这将确保正确发生之前/发生后行为.


当然你可以使用一个线程安全且更简单的枚举;)

enum Singleton {
    INSTANCE;
}
Run Code Online (Sandbox Code Playgroud)