zoukankan      html  css  js  c++  java
  • AtomicInteger源码

    一、概念

    AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。

    AtomicInteger的关键域只有一下3个:

     1     // setup to use Unsafe.compareAndSwapInt for updates
     2     private static final Unsafe unsafe = Unsafe.getUnsafe();
     3     private static final long valueOffset;
     4 
     5     static {
     6         try {
     7             valueOffset = unsafe.objectFieldOffset
     8                 (AtomicInteger.class.getDeclaredField("value"));
     9         } catch (Exception ex) { throw new Error(ex); }
    10     }
    11 
    12     private volatile int value;

    这里Unsafe是底层操作,valueOffset,value是volatile,

    关于Unsafe和CAS可参考该博文:http://www.cnblogs.com/xrq730/p/4976007.html

    二、属性

    核心方法 compareAndSet (int expect, int update) ,调用了Unsafe的compareAndSwapInt,其实就是CAS。而java.util.concurrent包就是建立在CAS上。

     1     /**
     2      * Atomically sets the value to the given updated value
     3      * if the current value {@code ==} the expected value.
     4      *
     5      * @param expect the expected value
     6      * @param update the new value
     7      * @return {@code true} if successful. False return indicates that
     8      * the actual value was not equal to the expected value.
     9      */
    10     public final boolean compareAndSet(int expect, int update) {
    11         return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    12     }

    AtomicInteger类下所有的方法都与之有关,比如 getAndIncrement()

    1     /**
    2      * Atomically increments by one the current value.
    3      *
    4      * @return the previous value
    5      */
    6     public final int getAndIncrement() {
    7         return unsafe.getAndAddInt(this, valueOffset, 1);
    8     }

    点进去发现其实也是调用的 compareAndSwapInt 方法

    1     public final int getAndAddInt(Object var1, long var2, int var4) {
    2         int var5;
    3         do {
    4             var5 = this.getIntVolatile(var1, var2);
    5         } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
    6 
    7         return var5;
    8     }

    ---------------------------------------------------多做多解决多总结------------------------------------------------

  • 相关阅读:
    Ubuntu下录音机程序的使用
    Bash中的数学计算
    Bash中的数学扩展
    Bash的命令替换
    top的用法
    VirtualBox的快照功能
    格式化输出和printf命令
    read命令读取用户输入
    Bash的作业控制
    Codeforces Round #455 (Div. 2)
  • 原文地址:https://www.cnblogs.com/sqy123/p/10497077.html
Copyright © 2011-2022 走看看