AtomicInteger源码解析

36 篇文章 0 订阅
34 篇文章 0 订阅

AtomicInteger,由于存储的值的value是volatile类型所有具有线程可见性。通过CAS比较交换进行自增,或者更新值具有原子性。所以AtomicInteger是线程安全的具有类锁一样的线程安全性。

具体参见下面源码解析:

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;


    static {
      try {
        valueOffset = unsafe.objectFieldOffset
            (AtomicInteger.class.getDeclaredField("value"));
      } catch (Exception ex) { throw new Error(ex); }
    }


    private volatile int value;//volatile保证了多线程之间的内存可见性


    /**
     * Creates a new AtomicInteger with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicInteger(int initialValue) {
        value = initialValue;
    }


    /**
     * Creates a new AtomicInteger with initial value {@code 0}.
     */
    public AtomicInteger() {

    }

//expect预期原值,update更新值,如果预期值等于原值,用更新值替换原值。替换成功返回true,否则返回false.具有volatile的读写内存语义。

    public final boolean compareAndSet(int expect, int update) {

return unsafe.compareAndSwapInt(this, valueOffset, expect, update);

    }

    public final int incrementAndGet() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return next;
        }

    }

    public final int decrementAndGet() {
        for (;;) {
            int current = get();
            int next = current - 1;
            if (compareAndSet(current, next))
                return next;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值