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

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

1、饿汉式

利用静态代码只执行一次实例化一个对象。

jdk中的类Runtime就是典型的饿汉式单例模式,该类描述了虚拟机一些信息。

Runtime的部分源码如下:

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}

	// ...
}

当然也可以用静态代码块,一个意思:

public class Singleton {
    private static Singleton instance = null;

    static {
        instance = new Singleton();
    }

    private Singleton (){}

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

2、静态内部类来实现:

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    private Singleton() { }

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

这种方式相比第1种有所优化,就是使用了lazy-loading。Singleton类被装载了,但是instance并没有立即初始化。

因为SingletonHolder类没有被主动使用,只有显示通过调用getInstance方法时,才会显示装载SingletonHolder类,从而实例化instance。


3、使用枚举的方式:

public enum Singleton {
	INSTANCE;
	
    public void otherMethod() {
    }
}

这种方式是Effective Java作者Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,可谓是很坚强的壁垒。不过目前很少被使用。


面试官:以上几种答案,其实现原理都是利用借助了类加载的时候初始化单例。即借助了ClassLoader的线程安全机制。

所谓ClassLoader的线程安全机制,就是ClassLoader的loadClass方法在加载类的时候使用了synchronized关键字。也正是因为这样, 除非被重写,这个方法默认在整个装载过程中都是同步的,也就是保证了线程安全。

所以,以上各种方法,虽然并没有显示的使用synchronized,但是还是其底层实现原理还是用到了synchronized。

面试官:除了这种以外,还有其他方式吗?

答:还可以使用Java并发包中的Lock实现。


4、Java并发包下的lock实现:

public class Singleton {
    private static Singleton instance;
    private static final Lock lock = new ReentrantLock();

    private Singleton() { }

    public static Singleton getInstance() {
        try {
            lock.lock();
            if (instance == null)
                instance = new Singleton();
            return instance;
        } finally {
            lock.unlock();
        }
    }
}

面试官:本质上还是在使用锁,不使用锁的话,有办法实现线程安全的单例吗?

答:有的,那就是使用CAS。


5、CAS实现:

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

public class Singleton {
	private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();

	private Singleton() { }

    public static Singleton getInstance() {
        for (;;) {
            Singleton singleton = INSTANCE.get();
            if (null != singleton) {
                return singleton;
            }

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值