【并发】2、AtomicReferenceFieldUpdater初体验

对于volatile对象的原子更新

AtomicReferenceFieldUpdater这个对象进行原子更新的时候,外部操作对象只能是public,因为外部访问不到private对象,但是在内内部确可以自己封装一个compareAndSet

package disruptor.test;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

import org.junit.Test;

/**
 * 基于反射的实用工具,可以对指定类的指定 volatile 字段进行原子更新。该类用于原子数据结构,该结构中同一节点的几个引用字段都独立受原子更新控制。
 * @author xiaof
 * 
 *  compareAndSet(T obj, V expect, V update)
 *  obj - 有条件地设置其字段的对象
 *  expect - 预期值
 *  update - 新值 
 *    如果当前值 == 预期值,则以原子方式将此更新器管理的给定对象的字段设置为给定的更新值。对 compareAndSet 和 set 的其他调用,此方法可以确保原子性,但对于字段中的其他更改则不一定确保原子性    
 *
 */
public class AtomicReferenceFieldUpdaterTest {

    @Test
    public void test1() {
        AtomicReferenceFieldUpdater update = AtomicReferenceFieldUpdater.newUpdater(Temp.class, String.class, "name2");
        Temp temp = new Temp();
        update.compareAndSet(temp, null, "66");
        update.compareAndSet(temp, "661", "6677");
        System.out.println(temp.name2);
        update.compareAndSet(temp, "66", "6677");
        System.out.println(temp.name2);
        
        //以下会报错
        /*
        AtomicReferenceFieldUpdater update2 = AtomicReferenceFieldUpdater.newUpdater(Temp.class, String.class, "name3");
        update2.compareAndSet(temp, null, "321");
        System.out.println(temp.name3);
        update2.compareAndSet(temp, null, "3211");
        System.out.println(temp.name3);
        update2.compareAndSet(temp, "321", "32112");
        System.out.println(temp.name3);
        */
        
        temp.compareAndSetName(null, "cutter");
        System.out.println("内部原子操作:" + temp.getName());
        temp.compareAndSetName3(null, "point");
        System.out.println("内部原子操作:" + temp.getName3());
        
    }
    
}


class Temp {
    private volatile String name;
    public volatile String name2;
    protected volatile String name3;
    
    public void compareAndSetName(String preValue, String name) {
        AtomicReferenceFieldUpdater update = AtomicReferenceFieldUpdater.newUpdater(Temp.class, String.class, "name");
        update.compareAndSet(this, preValue, name);
    }
    
    public void compareAndSetName3(String preValue, String name) {
        AtomicReferenceFieldUpdater update = AtomicReferenceFieldUpdater.newUpdater(Temp.class, String.class, "name3");
        update.compareAndSet(this, preValue, name);
    }
    
    public String getName() {
        return this.name;
    }
    
    public String getName3() {
        return this.name3;
    }
}

效果展示:

原文地址:https://www.cnblogs.com/cutter-point/p/8481323.html