Synchronized的內(nèi)部實(shí)現(xiàn)原理

我們都知道synchronized可以修飾方法和代碼塊,那么這兩者的內(nèi)部實(shí)現(xiàn)原理是相同的嗎匣砖?我們來仔細(xì)看一下。

修飾方法和代碼塊的不同

首先我們先看一下通過反編譯出的字節(jié)碼兩者有何不同欠动。
源代碼如下:

package jvm;

/**
 * Created by ljm on 29/1/2018.
 */
public class ClassCompile {
    synchronized void test(){}
    void test1(){
        synchronized (ClassCompile.class){

        }
    }
}

我們使用命令javap來反編譯:

javap -verbose ClassCompile

得到的字節(jié)碼如下(這里只截取與這里所說有關(guān)的部分):

synchronized void test();
    descriptor: ()V
    flags: ACC_SYNCHRONIZED
    Code:
      stack=0, locals=1, args_size=1
         0: return
      LineNumberTable:
        line 7: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       1     0  this   Ljvm/ClassCompile;

void test1();
    descriptor: ()V
    flags:
    Code:
      stack=2, locals=3, args_size=1
         0: ldc           #2                  // class jvm/ClassCompile
         2: dup
         3: astore_1
         4: monitorenter
         5: aload_1
         6: monitorexit
         7: goto          15
        10: astore_2
        11: aload_1
        12: monitorexit
        13: aload_2
        14: athrow
        15: return
      Exception table:
         from    to  target type
             5     7    10   any
            10    13    10   any

我們發(fā)現(xiàn)兩者在處理上是有不同的贸营。

  • 同步方法,JVM使用ACC_SYNCHRONIZED標(biāo)識(shí)來實(shí)現(xiàn)橙弱。即JVM通過在方法訪問標(biāo)識(shí)符(flags)中加入ACC_SYNCHRONIZED來實(shí)現(xiàn)同步功能歧寺。
  • 同步代碼塊,JVM使用monitorentermonitorexit兩個(gè)指令實(shí)現(xiàn)同步膘螟。即JVM為代碼塊的前后真正生成了兩個(gè)字節(jié)碼指令來實(shí)現(xiàn)同步功能的成福。
    然后我們分別對這兩個(gè)做詳細(xì)解釋。

同步方法

The Java? Virtual Machine Specification針對同步方法的說明:

Method-level synchronization is performed implicitly, as part of method invocation and return. A synchronized method is distinguished in the run-time constant pool’s method_info structure by the ACC_SYNCHRONIZED flag, which is checked by the method invocation instructions. When invoking a method for which ACC_SYNCHRONIZED is set, the executing thread enters a monitor, invokes the method itself, and exits the monitor whether the method invocation completes normally or abruptly. During the time the executing thread owns the monitor, no other thread may enter it. If an exception is thrown during invocation of the synchronized method and the synchronized method does not handle the exception, the monitor for the method is automatically exited before the exception is rethrown out of the synchronized method.

這段話適合好好讀讀荆残,大致含義如下:

同步方法是隱式的奴艾。一個(gè)同步方法會(huì)在運(yùn)行時(shí)常量池中的method_info結(jié)構(gòu)體中存放ACC_SYNCHRONIZED標(biāo)識(shí)符。當(dāng)一個(gè)線程訪問方法時(shí)内斯,會(huì)去檢查是否存在ACC_SYNCHRONIZED標(biāo)識(shí)蕴潦,如果存在,則先要獲得對應(yīng)的monitor鎖俘闯,然后執(zhí)行方法潭苞。當(dāng)方法執(zhí)行結(jié)束(不管是正常return還是拋出異常)都會(huì)釋放對應(yīng)的monitor鎖。如果此時(shí)有其他線程也想要訪問這個(gè)方法時(shí)真朗,會(huì)因得不到monitor鎖而阻塞此疹。當(dāng)同步方法中拋出異常且方法內(nèi)沒有捕獲,則在向外拋出時(shí)會(huì)先釋放已獲得的monitor鎖

第一句話解釋一下:

同步方法是隱式的。一個(gè)同步方法會(huì)在運(yùn)行時(shí)常量池中的method_info結(jié)構(gòu)體中存放ACC_SYNCHRONIZED標(biāo)識(shí)符蝗碎。

這句話的解讀是:我們從上面的反編譯結(jié)果也可以看到湖笨,同步方法會(huì)在class文件中的access_flags中存放ACC_SYNCHRONIZED,那這句話為什么說在運(yùn)行時(shí)常量池中呢蹦骑?
答:我們看看ACC_SYNCHRONIZED在class文件中的位置如下:

ACC_SYNCHRONIZE在class文件中的位置

可以看到ACC_SYNCHRONIZED標(biāo)識(shí)存放在常量池中慈省,而method_info結(jié)構(gòu)體中的access_flags字段是u2的,所以它只是一個(gè)指向常量池的標(biāo)記眠菇。而常量池在加載時(shí)就會(huì)加載到運(yùn)行時(shí)常量池中边败。所以這里解釋了為什么上面說ACC_SYNCHRONIZED在運(yùn)行時(shí)常量池中,而看class文件是存放在access_flags中的道理捎废。

同步代碼塊

同步代碼塊使用monitorentermonitorexit兩個(gè)指令實(shí)現(xiàn)同步笑窜, The Java? Virtual Machine Specification中有關(guān)于這兩個(gè)指令的介紹:

Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:

  • If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
    If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
  • If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.

大致含義如下:

每個(gè)對象都會(huì)與一個(gè)monitor相關(guān)聯(lián),當(dāng)某個(gè)monitor被擁有之后就會(huì)被鎖住缕坎,當(dāng)線程執(zhí)行到monitorenter指令時(shí)怖侦,就會(huì)去嘗試獲得對應(yīng)的monitor。步驟如下:

  1. 每個(gè)monitor維護(hù)著一個(gè)記錄著擁有次數(shù)的計(jì)數(shù)器谜叹。未被擁有的monitor的該計(jì)數(shù)器為0匾寝,當(dāng)一個(gè)線程獲得monitor(執(zhí)行monitorenter)后,該計(jì)數(shù)器自增變?yōu)?1 荷腊。
    • 當(dāng)同一個(gè)線程再次獲得該monitor的時(shí)候艳悔,計(jì)數(shù)器再次自增;
    • 當(dāng)不同線程想要獲得該monitor的時(shí)候女仰,就會(huì)被阻塞猜年。
  2. 當(dāng)同一個(gè)線程釋放 monitor(執(zhí)行monitorexit指令)的時(shí)候,計(jì)數(shù)器再自減疾忍。當(dāng)計(jì)數(shù)器為0的時(shí)候乔外。monitor將被釋放,其他線程便可以獲得monitor一罩。

The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.

這段好很好理解杨幼,大致含義如下:

當(dāng)線程執(zhí)行monitorexit指令時(shí),會(huì)去講monitor的計(jì)數(shù)器減一聂渊,如果結(jié)果是0差购,則該線程將不再擁有該monitor。其他線程就可以獲得該monitor了汉嗽。

總結(jié)一下

  • 同步方法和同步代碼塊底層都是通過monitor來實(shí)現(xiàn)同步的欲逃。
  • 兩者的區(qū)別:同步方式是通過方法中的access_flags中設(shè)置ACC_SYNCHRONIZED標(biāo)志來實(shí)現(xiàn);同步代碼塊是通過monitorenter和monitorexit來實(shí)現(xiàn)
  • 我們知道了每個(gè)對象都與一個(gè)monitor相關(guān)聯(lián)饼暑。而monitor可以被線程擁有或釋放稳析。

至此我們還有兩個(gè)問題沒有搞清楚:

  1. 到底啥是monitor洗做?
  2. 每個(gè)對象是如何與monitor關(guān)聯(lián)的?

我們下一篇文章細(xì)說迈着。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末竭望,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子裕菠,更是在濱河造成了極大的恐慌,老刑警劉巖闭专,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件奴潘,死亡現(xiàn)場離奇詭異,居然都是意外死亡影钉,警方通過查閱死者的電腦和手機(jī)画髓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來平委,“玉大人奈虾,你說我怎么就攤上這事×猓” “怎么了肉微?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蜡塌。 經(jīng)常有香客問我碉纳,道長,這世上最難降的妖魔是什么馏艾? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任劳曹,我火速辦了婚禮,結(jié)果婚禮上琅摩,老公的妹妹穿的比我還像新娘铁孵。我一直安慰自己,他們只是感情好房资,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布蜕劝。 她就那樣靜靜地躺著,像睡著了一般志膀。 火紅的嫁衣襯著肌膚如雪熙宇。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天溉浙,我揣著相機(jī)與錄音烫止,去河邊找鬼。 笑死戳稽,一個(gè)胖子當(dāng)著我的面吹牛馆蠕,可吹牛的內(nèi)容都是我干的期升。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼互躬,長吁一口氣:“原來是場噩夢啊……” “哼播赁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起吼渡,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對情侶失蹤容为,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后寺酪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體坎背,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年寄雀,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了得滤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡盒犹,死狀恐怖懂更,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情急膀,我是刑警寧澤沮协,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站脖阵,受9級(jí)特大地震影響皂股,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜命黔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一呜呐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧悍募,春花似錦蘑辑、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至喜鼓,卻和暖如春副砍,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背庄岖。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國打工豁翎, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人隅忿。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓心剥,卻偏偏與公主長得像邦尊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子优烧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

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