Aomic包下有四種數(shù)據(jù)類(lèi)型:AomicBoolean, AomicInteger, AomicLong和AomicReferrence(針對(duì)Object的)以及它們的數(shù)組類(lèi)型, 和相對(duì)應(yīng)的AtomicXXXFieldUpdater.
各種數(shù)據(jù)類(lèi)型中所有的原子操作都依賴(lài)于sun.misc.Unsafe這個(gè)類(lèi)和CAS操作.
sun.misc.Unsafe
Java是一個(gè)安全的開(kāi)發(fā)工具, 大部分的底層操作全部封裝在JNI中, 阻止開(kāi)發(fā)人員犯很多低級(jí)的錯(cuò)誤. 但是jdk依然提供了Unsafe類(lèi), 用于操作內(nèi)存. 事實(shí)上, jdk是禁止直接構(gòu)建Unsafe實(shí)例的, Unsafe.getUnsafe()只允許被JDK信任的類(lèi)調(diào)用, 如果直接調(diào)用會(huì)拋出SecutiryException.(進(jìn)一步了解https://dzone.com/articles/understanding-sunmiscunsafe.)
CAS
現(xiàn)代主流CPU都支持的一種硬件級(jí)別的原子操作, 比較并交換, 操作包含三個(gè)操作數(shù):
內(nèi)存位置(V)
預(yù)期原值(A)
新值(B)
如果內(nèi)存位置的值與預(yù)期原值相匹配, 那么處理器會(huì)自動(dòng)將該位置值更新為新值,否則, 處理器不做任何操作.無(wú)論哪種情況, 它都會(huì)在 CAS 指令之前返回該位置的值.
優(yōu)點(diǎn): 效率高, 無(wú)鎖
AtomicXXXX四種數(shù)值類(lèi)型
- value成員都是volatile:
保證寫(xiě)volatile變量會(huì)強(qiáng)制把CPU寫(xiě)緩存區(qū)的數(shù)據(jù)刷新到內(nèi)存;
讀volatile變量時(shí)赶站,使緩存失效把将,強(qiáng)制從內(nèi)存中讀取最新的值. - 基本方法get/set
- 主要方法:
compareAndSet,
weakCompareAndSet,
lazySet,
getAndSet: 取當(dāng)前值, 使用當(dāng)前值和準(zhǔn)備更新的值做CAS. - 對(duì)于Long和Integer
getAndIncrement/incrementAndGet,
getAndDecrement/decrementAndGet,
getAndAdd/addAndGet.
三組方法都和getAndSet,取當(dāng)前值曲横,加減之得到準(zhǔn)備更新的值草丧,再做CAS涩澡,/左右的區(qū)別在于返回的是當(dāng)前值還是更新值.
以AtomicInteger為例詳細(xì)說(shuō)明
1.成員變量
// setup to use Unsafe.compareAndSwapInt for updates
//如前所述, 用于直接操作內(nèi)存的類(lèi)
private static final Unsafe unsafe = Unsafe.getUnsafe();
//內(nèi)存中,成員變量的地址相對(duì)于對(duì)象的偏移量
private static final long valueOffset;
//利用unsafe計(jì)算偏移量valueOffset
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
//存儲(chǔ)int值
//volatile保證了新值能立即同步到主內(nèi)存,以及每次使用前立即從主內(nèi)存刷新.
//當(dāng)把變量聲明為volatile類(lèi)型后,編譯器與運(yùn)行時(shí)都會(huì)注意到這個(gè)變量是共享的.
private volatile int value;
2.構(gòu)造函數(shù)
/**
* 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() {
}
3.get/set
/**
* 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;
}
4.主要方法
/**
* Eventually sets to the given value.
* @param newValue the new value
* @since 1.6
*/
//putOrderedXXX方法是putXXXVolatile方法的延遲實(shí)現(xiàn)智蝠,不保證值的改變被其他線(xiàn)程立即看到.
//volatile變量的修改可以立刻讓所有的線(xiàn)程可見(jiàn),lazySet說(shuō)白了就是以普通變量的方式來(lái)寫(xiě)變量
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) {
for (;;) {
int current = get();
if (compareAndSet(current, newValue))
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);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return 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() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* 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) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* 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) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, 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());
}
public int intValue() {
return get();
}
public long longValue() {
return (long)get();
}
public float floatValue() {
return (float)get();
}
public double doubleValue() {
return (double)get();
}