java.util.concurrent源碼閱讀 02 關(guān)于java.util.concurrent.atomic包

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)型

  1. value成員都是volatile:
    保證寫(xiě)volatile變量會(huì)強(qiáng)制把CPU寫(xiě)緩存區(qū)的數(shù)據(jù)刷新到內(nèi)存;
    讀volatile變量時(shí)赶站,使緩存失效把将,強(qiáng)制從內(nèi)存中讀取最新的值.
  2. 基本方法get/set
  3. 主要方法:
    compareAndSet,
    weakCompareAndSet,
    lazySet,
    getAndSet: 取當(dāng)前值, 使用當(dāng)前值和準(zhǔn)備更新的值做CAS.
  4. 對(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();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市亥揖,隨后出現(xiàn)的幾起案子珊擂,更是在濱河造成了極大的恐慌,老刑警劉巖费变,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件摧扇,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡挚歧,警方通過(guò)查閱死者的電腦和手機(jī)扛稽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)昼激,“玉大人庇绽,你說(shuō)我怎么就攤上這事锡搜〕壤В” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵耕餐,是天一觀(guān)的道長(zhǎng)凡傅。 經(jīng)常有香客問(wèn)我,道長(zhǎng)肠缔,這世上最難降的妖魔是什么夏跷? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任哼转,我火速辦了婚禮,結(jié)果婚禮上槽华,老公的妹妹穿的比我還像新娘壹蔓。我一直安慰自己,他們只是感情好猫态,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布佣蓉。 她就那樣靜靜地躺著,像睡著了一般亲雪。 火紅的嫁衣襯著肌膚如雪勇凭。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天义辕,我揣著相機(jī)與錄音虾标,去河邊找鬼。 笑死灌砖,一個(gè)胖子當(dāng)著我的面吹牛璧函,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播基显,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼柳譬,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了续镇?” 一聲冷哼從身側(cè)響起美澳,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎摸航,沒(méi)想到半個(gè)月后制跟,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡酱虎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年雨膨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片读串。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡聊记,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出恢暖,到底是詐尸還是另有隱情排监,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布杰捂,位于F島的核電站舆床,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜挨队,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一谷暮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧盛垦,春花似錦湿弦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至俯在,卻和暖如春竟秫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背跷乐。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工肥败, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人愕提。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓馒稍,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親浅侨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子纽谒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容