【并发】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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值