AtomicReference
主要是compareAndSet,将比较对象的地址、设置新增作为CAS原子操作
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
简单示例
public class MyAtomicReference {
static AtomicReference<UserInfo> atomicUserRef;
public static void main(String[] args) {
//要修改的实体的实例
UserInfo user = new UserInfo("Mark", 15);
atomicUserRef = new AtomicReference(user);
System.out.println("user修改之前age=15 "+atomicUserRef.get());
user.setAge(10);
System.out.println("user修改之后age=10,AtomicReference的值="+atomicUserRef.get()+" 也发生了改变,所以AtomicReference指向是地址引用");
UserInfo updateUser = new UserInfo("Bill",17);
//通过比较对象use和atomicUserRef存储对象地址是否相同,来更新atomicUserRef的引用值
atomicUserRef.compareAndSet(user,updateUser);
System.out.println("compareAndSet之后的结果"+atomicUserRef.get());
System.out.println("user:"+user);
System.out.println("updateUser:"+updateUser);
}
/**
* 定义一个实体类
*/
static class UserInfo {
private volatile String name;
private int age;
public UserInfo(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
结果:
user修改之前age=15UserInfo{name='Mark', age=15}
user修改之后age=10,AtomicReference的值=UserInfo{name='Mark', age=10} 也发生了改变,所以AtomicReference指向是地址引用
compareAndSet之后的结果UserInfo{name='Bill', age=17}
user:UserInfo{name='Mark', age=10}
updateUser:UserInfo{name='Bill', age=17}