我們都知道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使用monitorenter和monitorexit兩個(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_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中的道理捎废。
同步代碼塊
同步代碼塊使用monitorenter和monitorexit兩個(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。步驟如下:
- 每個(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ì)被阻塞猜年。
- 當(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è)問題沒有搞清楚:
- 到底啥是monitor洗做?
- 每個(gè)對象是如何與monitor關(guān)聯(lián)的?
我們下一篇文章細(xì)說迈着。