普通变量变为原子变量——AtomicIntegerFieldUpdater

有的时候我们不需要直接申明一个原子变量,比如申明一个AtomicInteger对象,因为原子变量本身就影响性能,还有就是只是偶尔进行原子操作,比如在某一时刻段,那么这个时候AtomicIntegerFieldUpdater或者AtomicLongFieldUpdater就显得比较有用了,以AtomicIntegerFieldUpdater为例子,基于反射的实用程序,可以对指定类的指定的volatile int字段进行原子更新

重要方法

 @CallerSensitive
    public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass,
                                                              String fieldName) {
        return new AtomicIntegerFieldUpdaterImpl<U>
            (tclass, fieldName, Reflection.getCallerClass());
    }

通过传入目标类和目标类的变量,对变量进行原子升级,通过反射返回AtomicIntegerFieldUpdater对象,通过这个对象就可以对这个变量进行原子操作

注意这个变量不能是静态和私有的
案例:

/**
 * 描述:     演示AtomicIntegerFieldUpdater的用法
 */
public class AtomicIntegerFieldUpdaterDemo implements Runnable{

    static Candidate tom;
    static Candidate peter;

    public static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater
            .newUpdater(Candidate.class, "score");

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            peter.score++;
            scoreUpdater.getAndIncrement(tom);
        }
    }

    public static class Candidate {
//不能被static修饰,也不能为私有
        volatile int  score;
    }

    public static void main(String[] args) throws InterruptedException {
        tom=new Candidate();
        peter=new Candidate();
        AtomicIntegerFieldUpdaterDemo r = new AtomicIntegerFieldUpdaterDemo();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("普通变量:"+peter.score);
        System.out.println("升级后的结果"+ tom.score);
    }
}

执行结果:
普通变量:19128
升级后的结果20000

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章