Java并发来一发(十一)Java中的原子操作类

一、原子操作类简介

JDK1.5开始提供了java.util.concurrent.atomic包,其中有一系列用法简单、性能高效、可以线程安全更新变量的原子操作类,目前(JDK1.7)大概有这么些:

二、原子操作类实现原理

以AtomicInteger为例看下源码,其中的两个方法getAndSet,getAndIncrement,都是无限循环调用compareAndSet,直到成功,CAS方法调用的是unsafe的方法,目前unsafe限制越来越严,也不建议程序员使用了,这里不做分析。源码如下:

public class AtomicInteger extends Number implements java.io.Serializable {
    

    /**
     * Atomically sets to the given value and returns the old value.
     *
     * @param newValue the new value
     * @return the previous value
     */
    public final int getAndSet(int newValue) {
        for (;;) {
            int current = get();
            if (compareAndSet(current, newValue))
                return current;
        }
    }


    /**
     * Atomically increments by one the current value.
     *
     * @return the previous value
     */
    public final int getAndIncrement() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return current;
        }
    }


    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }



}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值