一晴弃、前言
AtomicInteger基于CAS(Compare and Swap袱瓮,比較并修改)的操作宛瞄,主要實(shí)現(xiàn)樂觀鎖的思想瘫辩。
對(duì)于傳統(tǒng)的悲觀鎖來說,會(huì)假設(shè)線程并發(fā)非常重,每次修改數(shù)據(jù)承绸,一定先100%確保自己進(jìn)入安全區(qū)挣轨,再安心修改目標(biāo)值卷扮。進(jìn)而出現(xiàn)線程在競(jìng)爭(zhēng)鎖的過程中消耗大量時(shí)間在等待鎖摩幔、加鎖或衡、解鎖等操作上封断。(注:鎖還可能涉及鎖自旋坡疼、公平鎖等知識(shí)點(diǎn)柄瑰,而非簡(jiǎn)單暴力競(jìng)爭(zhēng))
相比之下的樂觀鎖剪况,會(huì)假設(shè)只有自己一個(gè)線程修改目標(biāo)值,先比較修改前的值是不是和自己的預(yù)期的一致镐作,一致就修改并返回,不一致就放棄這次修改(CAS)杨蛋,并發(fā)起下一次的嘗試逞力,不會(huì)把時(shí)間用在加鎖和解鎖上寇荧。
雖然樂觀鎖看起來比悲觀鎖好很多户侥,不過樂觀鎖主要用在單個(gè)值(Int,F(xiàn)loat替梨,Double)的并發(fā)修改上,而不是悲觀鎖對(duì)一個(gè)對(duì)象甚至是一個(gè)代碼塊的操作俗扇。
其次,若樂觀鎖對(duì)目標(biāo)值修改操作次數(shù)遠(yuǎn)多于讀取操作箕别,那么CAS實(shí)際也會(huì)大量失敗抵消CAS的優(yōu)點(diǎn)铜幽,并演變成成多次重試失效。
說到CAS串稀,需要了解的是這個(gè)能力并非由操作系統(tǒng)或JVM提供除抛,而是CPU原生支持的。如果一個(gè)CPU不能保證CAS能力母截,那這個(gè)CPU的完全沒有數(shù)據(jù)修改安全可言到忽。
說回AtomicInteger
,這類不能看見底層的運(yùn)作清寇,因?yàn)橹饕{(diào)用了Unsafe
實(shí)現(xiàn)CAS喘漏。以后會(huì)寫關(guān)于Unsafe
的文章,敬請(qǐng)期待华烟。
二翩迈、類簽名
由于集成了Number
,所以任何能接受Number
類型的形參都能使用AtomicInteger
public class AtomicInteger extends Number implements java.io.Serializable
三盔夜、靜態(tài)初始化
在靜態(tài)初始化塊里面獲取value
的內(nèi)存地址负饲,這時(shí)的value
內(nèi)存地址已經(jīng)開辟堤魁,但是沒有被實(shí)例初始化。而靜態(tài)初始化塊是類初始化最早調(diào)用的返十,靜態(tài)初始化安全由JVM來保證妥泉。
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
四、數(shù)據(jù)成員
volatile保證value值的有序性和可見性吧慢,不保證原子性涛漂。原子性一般由synchronized或Lock來提供支持。
private volatile int value;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
五检诗、構(gòu)造方法
// 用一個(gè)給定的整形值初始化一個(gè)AtomicInteger實(shí)例
public AtomicInteger(int initialValue) {
value = initialValue;
}
// 初始化一個(gè)值為0的AtomicInteger實(shí)例
public AtomicInteger() {
}
六匈仗、成員方法
// 獲取當(dāng)前的整形值,線程不安全
public final int get() {
return value;
}
// 設(shè)置新的整形值逢慌,線程不安全
public final void set(int newValue) {
value = newValue;
}
// 最終一定會(huì)把newValue設(shè)置成功
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
// 設(shè)置新的整形值悠轩,把返回上一個(gè)保存的值
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
如果待修改的值和期待值相同,那就把待修改的值設(shè)置為update的值
偽代碼: value == expect ? value = update; return isModified;
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.
*
* <p><a href="package-summary.html#weakCompareAndSet">May fail
* spuriously and does not provide ordering guarantees</a>, 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);
}
// 先返回上一個(gè)值攻泼,然后再在原基礎(chǔ)上自增1
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
// 先返回上一個(gè)值火架,然后再在原基礎(chǔ)上自減1
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
// 返回上一個(gè)值,并在原基礎(chǔ)上加上指定值
// 偽代碼: oldValue = value; value += delta; return oldValue;
public final int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
// 先自增忙菠,然后返回自增后的值
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
// 先自減何鸡,然后返回自減后的值
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
// 先增加delta的值,然后返回增加后的值
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
七牛欢、Java8 Lambda支持
IntUnaryOperator -> This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
/**
* 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;
}
八骡男、參考鏈接
https://docs.oracle.com/javase/8/docs/api/java/util/function/IntUnaryOperator.html
https://docs.oracle.com/javase/8/docs/api/java/util/function/IntBinaryOperator.html