java AtomicInteger 類使用詳解

前言

在文章開始之前, 我們首先將這個類分解一下,第一部分是 Atomic ,Atomic代表原子的意思,而後面是 Integer,代表int類型的數據,也就是表示這個int類型的操作是一個原子操作。

首先我們想一下,為什麼要有原子操作,在進行併發編程的時候我們需要確保程序在被多個線程併發訪問時可以得到正確的結果,也就是實現線程安全。線程安全的定義如下:

當多個線程訪問某個類時,不管運行時環境採用何種調度方式或者這些線程將如何交替執行,並且在主調代碼中不需要任何額外的同步或協同,這個類都能表現出正確的行為,那麼這個類就是線程安全的。

java AtomicInteger 類使用詳解

舉個線程不安全的例子。假如我們想實現一個功能來統計網頁訪問量,你可能想到用count++ 來統計訪問量,但是這個自增操作不是線程安全的。count++ 可以分成三個操作:

1.獲取變量當前值
2.給獲取的當前變量值+1
3.寫回新的值到變量

假設count的初始值為1,當進行併發操作的時候,可能出現線程A和線程B都進行到了1操作,之後又同時進行2操作。A先進行到3操作+1,現在值為2;注意剛才AB獲取到的當前值都是1,所以B執行3操作後,count的值依然是2。這個結果顯然不符合我們的要求。這也就是不符合原子操作,也就是線程不安全的。

我們面對這樣的情況應該如何去解決那?

1.我們可以在這段代碼中加上 synchronized 關鍵字,讓這段程序在同一時間只能被一個線程所執行,但是我們發現了一個致命的問題,就是我們使用了synchronized 機制,讓這個函數都加了鎖,使程序的效率降低,那麼我們有沒有方法即能讓程序的效率不降低,又能實現原子操作那 atomic 類就登場了。

所以我們需要用本篇的主角—— AtomicInteger 來保證線程安全。

首先,我們看下源碼

這段太長,可以直接掠過回看。

package java.util.concurrent.atomic;
import java.util.function.IntUnaryOperator;
import java.util.function.IntBinaryOperator;
import sun.misc.Unsafe;
/**
* An {@code int} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An
* {@code AtomicInteger} is used in applications such as atomically
* incremented counters, and cannot be used as a replacement for an
* {@link java.lang.Integer}. However, this class does extend
* {@code Number} to allow uniform access by tools and utilities that
* deal with numerically-based classes.
*
* @since 1.5
* @author Doug Lea
*/
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// 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;
/**
* 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() {
}
/**
* Gets the current value.
*
* @return the current value
*/
public final int get() {
return value;
}
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(int newValue) {
value = newValue;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* Atomically sets the value to the given updated value

* if the current value {@code ==} the expected value.
*
*

, so is
* only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
/**
* 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);
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value


*/
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
/**
* 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;
}
/**
* Atomically updates the current value with the results of
* applying the given function, returning the updated 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 updated value
* @since 1.8
*/
public final int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return next;
}
/**

* Atomically updates the current value with the results of
* applying the given function to the current and given values,
* 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. The function
* is applied with the current value as its first argument,
* and the given update as the second argument.
*
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the previous value
* @since 1.8
*/
public final int getAndAccumulate(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* Atomically updates the current value with the results of
* applying the given function to the current and given values,
* returning the updated value. The function should be
* side-effect-free, since it may be re-applied when attempted
* updates fail due to contention among threads. The function
* is applied with the current value as its first argument,
* and the given update as the second argument.
*
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the updated value
* @since 1.8
*/
public final int accumulateAndGet(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return next;
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value
*/
public String toString() {

return Integer.toString(get());
}
/**
* Returns the value of this {@code AtomicInteger} as an {@code int}.
*/
public int intValue() {
return get();
}
/**
* Returns the value of this {@code AtomicInteger} as a {@code long}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public long longValue() {
return (long)get();
}
/**
* Returns the value of this {@code AtomicInteger} as a {@code float}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public float floatValue() {
return (float)get();
}
/**
* Returns the value of this {@code AtomicInteger} as a {@code double}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public double doubleValue() {
return (double)get();
}

我們從中抽出幾個重要方法

-boolean compareAndSet(int expect, int update)
這個方法主要用於比較賦值,也就是說會先取值,然後和expect值進行比較,如果這兩個值相同,則更新成新的值,如果不同,則不更新,這裡面的返回值是是否更新成功。
非常重要:為什麼要比較賦值,我們可以想象一下,什麼時候內存裡面的值和expect不相同,也就是說,在沒進行比較之前,except賦值之後(因為我們要先進行對except賦值),內存中的結果被改變了,也就是另外一個線程操作了這個數字,那麼我們此時,如果對這個數字進行改變,就變得非常不安全了,因為另外一個線程可能要用這個數字對其他值進行賦值操作。所以這個操作是實現原子操作的根本所在。

用CAS操作實現安全的自增

AtomicInteger中有很多方法,例如incrementAndGet() 相當於i++ 和getAndAdd() 相當於i+=n 。從源碼中我們可以看出這幾種方法的實現很相似,所以我們主要分析incrementAndGet() 方法的源碼。

源碼如下:

 public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

incrementAndGet() 方法實現了自增的操作。核心實現是先獲取當前值和目標值(也就是value+1),如果compareAndSet(current, next) 返回成功則該方法返回目標值。那麼compareAndSet是做什麼的呢?理解這個方法我們需要引入CAS操作。

在大學操作系統課程中我們學過獨佔鎖和樂觀鎖的概念。獨佔鎖就是線程獲取鎖後其他的線程都需要掛起,直到持有獨佔鎖的線程釋放鎖;樂觀鎖是先假定沒有衝突直接進行操作,如果因為有衝突而失敗就重試,直到操作成功。其中樂觀鎖用到的機制就是CAS,Compare and Swap。

AtomicInteger 中的CAS操作就是compareAndSet(),其作用是每次從內存中根據內存偏移量(valueOffset)取出數據,將取出的值跟expect 比較,如果數據一致就把內存中的值改為update。

這樣使用CAS就保證了原子操作。其餘幾個方法的原理跟這個相同,在此不再過多的解釋。

沒看AtomicInteger 源碼之前,我認為其內部是用synchronized 來實現的原子操作。查閱資料後發現synchronized 會影響性能,因為Java中的synchronized 鎖是獨佔鎖,雖然可以實現原子操作,但是這種實現方式的併發性能很差。


分享到:


相關文章: