在看spring reactor 源码之际,在其中使用了AtomicReferenceFieldUpdater,在此记录一下。
作用
这是一个基于反射的工具类,它能对指定类的【指定的volatile引用字段】进行【原子更新】。(注意这个字段不能是private的)
简单理解:就是对某个类中,被volatile修饰的字段进行原子更新。
用法
此类接收三个参数:
1、字段所在的类。
2、字段的类型。
3、更新字段的内容。
例如:
AtomicReferenceFieldUpdater updater= AtomicReferenceFieldUpdater.newUpdater(Person .class, String.class, "name");
Person person = new Person;
updater.compareAndSet(person ,person .name,"老王") ;
System.out.println(Person .name);
class Person {
volatile String name="老刘";
}
[参考文档]
https://www.iteye.com/blog/huangyunbin-1944153