JDK源碼分析-AtomicInteger

來源:互聯網
上載者:User

標籤:reads   參數   原子操作   分配   when   支援   並發   erro   this   

  AtomicInteger可以看做Integer類的原子操作工具類。在java.util.concurrent.atomic包下,在一些使用場合下可以取代加鎖操作提高並發性。接下來就從幾個方面來介紹:

  1.原子性和CAS。

  2.CPU底層實現原理。

  3.atomic包介紹。

  4.源碼分析。

  原子性和CAS

  原子性就是指某一個操作是不可拆分的,是一個整體必須要一次性全部執行完成要麼就不執行。

  CAS是Compare And Swap(比較並交換)。意思是當你要更新某個值的時候先要檢查這個變數的當前值是不是改變了,如果改變了就不能更新,沒改變就可以更新。

  首先,CPU 會將記憶體中將要被更改的資料與期望的值做比較。然後,當這兩個值相等時,CPU 才會將記憶體中的數值替換為新的值。否則便不做操作。最後,CPU 會將舊的數值返回。這一系列的操作是原子的。它們雖然看似複雜,但卻是 Java 5 並發機制優於原有鎖機制的根本。簡單來說,CAS 的含義是“我認為原有的值應該是什麼,如果是,則將原有的值更新為新值,否則不做修改,並告訴我原來的值是多少。

  atomic包介紹

  類的小工具包,支援在單個變數上解除鎖的安全執行緒編程。此包中的類可將 volatile 值、欄位和數組元素的概念擴充到那些也提供原子條件更新操作的類,其形式如下:

boolean compareAndSet(expectedValue, updateValue);

  如果此方法(在不同的類間參數類型也不同)當前保持 expectedValue,則以原子方式將變數設定為 updateValue,並在成功時報告 true。此包中的類還包含擷取並無條件設定值的方法,以及以下描述的較弱條件的原子更新操作 weakCompareAndSet。

  原子訪問和更新的記憶體效果一般遵循以下可變規則:

  • get 具有讀取 volatile 變數的記憶體效果。
  • set 具有寫入(分配)volatile 變數的記憶體效果。
  • 除了允許使用後續(但不是以前的)記憶體操作,其自身不施加帶有普通的非 volatile 寫入的重新排序約束,lazySet 具有寫入(分配)volatile 變數的記憶體效果。在其他使用上下文中,當為 null 時(為了記憶體回收),lazySet 可以應用不會再次訪問的引用。
  • weakCompareAndSet 以原子方式讀取和有條件地寫入變數但不建立任何 happen-before 排序,因此不提供與除 weakCompareAndSet 目標外任何變數以前或後續讀取或寫入操作有關的任何保證。
  • compareAndSet 和所有其他的讀取和更新操作(如 getAndIncrement)都有讀取和寫入 volatile 變數的記憶體效果。

  設計原子類主要用作各種構造塊,用於實現非阻塞資料結構和相關的基礎結構類。compareAndSet 方法不是鎖的常規替換方法。僅當對象的重要更新限定於單個 變數時才應用它。原子類不是 java.lang.Integer 和相關類的通用替換方法。它們不 定義諸如 hashCode 和 compareTo 之類的方法。

  源碼舉例分析

  AtomicInteger繼承結構:

  -java.lang.Object

  ---java.lang.Number

  ------java.util.concurrent.atomic.AtomicInteger

  還實現了java.io.Serializable以便序列化使用,然後是欄位的定義和初始化:

  Unsafe裡面定義了許多Native方法,通過JNI調用。value就是AtomicInteger代表的值,這裡用volatile修飾用以保證value的可見度。

  //源碼 setup to use Unsafe.compareAndSwapInt for updates    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;

  AtomicInteger大概實現了20個左右的public方法,下面舉幾個有代表性的來分析:

  1.get方法是用來擷取當前最新的value。方法用final修飾是為了更進一步的保證安全執行緒。

    /**     * Gets the current value.     *     * @return the current value     */    public final int get() {        return value;    }

  2.set方法是把value更新為一個新值。也是用final修飾。

    /**     * Sets to the given value.     *     * @param newValue the new value     */    public final void set(int newValue) {        value = newValue;    }

  3.lazySet方法和set方法不同之處在於可以延時設定,就是在最後才設定新值。

    /**     * Eventually sets to the given value.     *     * @param newValue the new value     * @since 1.6     */    public final void lazySet(int newValue) {        unsafe.putOrderedInt(this, valueOffset, newValue);    }

  4.getAndSet方法是把新值設定為當前值然後返回舊值。

    /**     * 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) {        return unsafe.getAndSetInt(this, valueOffset, newValue);    }

  5.compareAndSet方法是首先比較當前值與期望值,相同才更新到新值。如果更新成功則返回true,否則返回false。

    /**     * 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 {@code 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);    }

  6.getAndIncrement方法是原子的把原值加一併且返回舊值。getAndDecrement類似。

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

  7.getAndAdd方法是把原值加上某個值,並返回以前的值。

    /**     * Atomically adds the given value to the current value.     *     * @param delta the value to add     * @return the previous value     */    public final int getAndAdd(int delta) {        return unsafe.getAndAddInt(this, valueOffset, delta);    }

  8.incrementAndGet方法是把原值加一後返回新值。decrementAndGet類似。

    /**     * Atomically increments by one the current value.     *     * @return the updated value     */    public final int incrementAndGet() {        return unsafe.getAndAddInt(this, valueOffset, 1) + 1;    }

  9.getAndUpdate方法是根據一個定義的操作符來把當前值當第一個參數,傳入的參數當做第二個參數更新value,返回舊值。updateAndGet是返回新值。 使用自旋的方式,調用了compareAndSet方法,只有返回了true才結束。

    /**     * Atomically updates the current value with the results of     * applying the given function, returning the previous value. The     * function should be side-effect-free, since it may be re-applied     * when attempted updates fail due to contention among threads.     *     * @param updateFunction a side-effect-free function     * @return the previous value     * @since 1.8     */    public final int getAndUpdate(IntUnaryOperator updateFunction) {        int prev, next;        do {            prev = get();            next = updateFunction.applyAsInt(prev);        } while (!compareAndSet(prev, next));        return prev;    }

  以上這些方法都是原子操作。

  

  

  

  

 

JDK源碼分析-AtomicInteger

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.