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.”
即可以通过原子的方式更新引用,