【面试】不使用synchronized和lock,如何实现一个线程安全的单例

import java.util.concurrent.atomic.AtomicReference;


public class HungrySingleton {

    private static HungrySingleton instance = new HungrySingleton();

    private HungrySingleton() {
    }


    public static HungrySingleton getInstance() {
        return instance;
    }
}

/**
 * 饿汉
 */
class HungrySingleton2 {

    private static HungrySingleton2 instance;

    static {

        instance = new HungrySingleton2();
    }

    private HungrySingleton2() {
    }


    public static HungrySingleton2 getInstance() {
        return instance;
    }
}

/**
 * lazy-loading
 */
class LazyLoadingSingleton {

    private static class SingletonHolder {
        private static final LazyLoadingSingleton instance = new LazyLoadingSingleton();
    }

    private LazyLoadingSingleton() {
    }

    public static final LazyLoadingSingleton getInstance() {
        return SingletonHolder.instance;
    }


}


class EnumSingleton {

    private EnumSingleton() {
    }

    public static EnumSingleton getInstance() {
        return Singleton.INSTANCE.getInstance();
    }

    enum Singleton {
        INSTANCE;

        /**
         * 单例
         */
        private EnumSingleton singleton;

        //JVM会保证此方法绝对只调用一次
        private Singleton() {
            singleton = new EnumSingleton();
        }

        public EnumSingleton getInstance() {
            return singleton;
        }
    }
}

class CasSingleton {

    private static final AtomicReference INSTANCE = new AtomicReference();

    private CasSingleton() {}

    public static final CasSingleton getInstance() {

        while (true) {
            CasSingleton singleton =  INSTANCE.get();

            if (singleton != null) {
                return singleton;
            }
            singleton = new CasSingleton();
            INSTANCE.compareAndSet(null,singleton);
            return singleton;
            

        }
    }

}

你可能感兴趣的:(【面试】不使用synchronized和lock,如何实现一个线程安全的单例)