不使用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
    评论
下面是一个示,演示了如何在Java中实现无锁并发代码,而不使用Atomic、synchronizedLock。 ```java public class NoLockConcurrencyExample { private static volatile int counter = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new IncrementTask()); Thread t2 = new Thread(new IncrementTask()); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Counter value: " + counter); } static class IncrementTask implements Runnable { @Override public void run() { for (int i = 0; i < 10000; i++) { incrementCounter(); } } } private static void incrementCounter() { int oldValue; int newValue; do { oldValue = counter; newValue = oldValue + 1; } while (!compareAndSet(oldValue, newValue)); } private static boolean compareAndSet(int expect, int update) { if (counter == expect) { counter = update; return true; } return false; } } ``` 在这个示中,我们使用一个volatile修饰的counter变量来存储计数器的值。volatile关键字确保了多线程之间的可见性,即一个线程修改了counter的值,其他线程能够立即看到最新的值。 在IncrementTask任务中,我们使用一个自定义的incrementCounter方法来递增计数器的值。该方法使用了一个自旋的compare-and-set循环,不断尝试修改counter的值直到成功。compareAndSet方法通过比较当前counter的值和期望的值,如果相等则更新为新值。 这种无锁的实现方式利用了volatile关键字的可见性和CAS(Compare-and-Swap)操作的原子性,避免了使用显式锁,从而实现了无锁并发。 需要注意的是,这个示只是一个简的演示,并不适用于所有场景。在实际开发中,需要仔细评估使用无锁并发的适用性和性能,并根据具体需求进行选择。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值