AtomicReference
- 在阅读设计模式时,发现一种单例模式的实现方式,是通过AtomicReference来实现
public class Singleton_06 {
private static final AtomicReference<Singleton_06> INSTANCE = new AtomicReference<Singleton_06>();
private static Singleton_06 instance;
private Singleton_06(){}
public static final Singleton_06 getInstance(){
for (;;){
Singleton_06 instance = INSTANCE.get();
if (null != instance) return instance;
INSTANCE.compareAndSet(null, new Singleton_06());
return INSTANCE.get();
}
}
public static void main(String[] args) {
System.out.println(Singleton_06.getInstance());
System.out.println(Singleton_06.getInstance());
}
}
-
AtomicReference的作用
源码中是这样写的:“An object reference that may be updated atomically.”
即可以通过原子的方式更新引用,它是基于cas实现的,使用cas的好处就是不需要使用传统的加锁方式保证线程安全,而是依赖于cas的忙等算法,依赖于底层硬件实现来保证线程安全。相对于其他锁的实现没有现场切换和阻塞,也就没有了额外的开销,并且可以支持较大的并发性。(当然cas也有一个缺点就是忙等,如果一直没有获取到将会处于死循环中。) -
AtomicReference常用API
//创建对象,并将引用传给AtomicReference对象
String originValue = "origin";
AtomicReference<String> atomicReference = new AtomicReference<String>(originValue);
String value = atomicReference.get(); //获取到AtomicReference中的引用对象
String newValue = "new value";
boolean exchanged = atomicReference.compareAndSet(originValue, newValue);
// compareAndSet方法会比较当前AtomicReference对象中的引用的是否是originValue,如果是,则会更新为newValue
如果不是,则不会更新

本文介绍了Java中的AtomicReference,它用于原子性地更新对象引用。AtomicReference基于CAS实现,提供了一种无锁的线程安全策略,相比传统锁具有更高的并发性能。文章探讨了其作用和优点,并提及了CAS的忙等特性及其可能的死循环问题。同时,还列举了AtomicReference的一些常用API。


被折叠的 条评论
为什么被折叠?



