通過sychronized給對(duì)象加鎖,每個(gè)對(duì)象在實(shí)例化后,會(huì)同時(shí)實(shí)例出一個(gè)ObjectMoniter头朱,同時(shí)對(duì)象有對(duì)象頭(markOop
)座享,在對(duì)象頭中會(huì)存有當(dāng)前鎖狀態(tài)信息婉商,包含線程id似忧。
ObjectMoniter
objectMonitor.hpp
ObjectMonitor() {
_header = NULL;
_count = 0;
_waiters = 0,
_recursions = 0;
_object = NULL;
_owner = NULL;
_WaitSet = NULL;
_WaitSetLock = 0 ;
_Responsible = NULL ;
_succ = NULL ;
_cxq = NULL ;
FreeNext = NULL ;
_EntryList = NULL ;
_SpinFreq = 0 ;
_SpinClock = 0 ;
OwnerIsThread = 0 ;
_previous_owner_tid = 0;
}
_count:當(dāng)有對(duì)象獲取鎖,count+1丈秩,對(duì)象釋放鎖count-1
_EntryList:當(dāng)有對(duì)象嘗試獲取鎖盯捌,加入entryList中
_WaitSet:當(dāng)調(diào)用wait方法,進(jìn)入等待隊(duì)列
_owner:擁有鎖當(dāng)線程蘑秽,當(dāng)鎖釋放是饺著,count-1同時(shí)owner置為NULL
當(dāng)使用sychronized給對(duì)象加鎖時(shí),字節(jié)碼中是monitorenter給指定對(duì)象加鎖筷狼,給靜態(tài)方法加鎖時(shí)瓶籽,使用ACC_SYNCHRONIZED標(biāo)志給當(dāng)前對(duì)象加鎖。
public class SychronizedTest {
private final Object lock = new Object();
private volatile int count;
public synchronized void method1() {
count++;
}
public void method2() {
synchronized (lock) {
count++;
}
}
}
bytecode
public synchronized void method1();
descriptor: ()V
flags: ACC_PUBLIC, ACC_SYNCHRONIZED
Code:
stack=3, locals=1, args_size=1
0: aload_0
1: dup
2: getfield #4 // Field count:I
5: iconst_1
6: iadd
7: putfield #4 // Field count:I
10: return
LineNumberTable:
line 14: 0
line 15: 10
LocalVariableTable:
Start Length Slot Name Signature
0 11 0 this Lcom/chao/SychronizedTest;
public void method2();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=3, locals=3, args_size=1
0: aload_0
1: getfield #3 // Field lock:Ljava/lang/Object;
4: dup
5: astore_1
6: monitorenter
7: aload_0
8: dup
9: getfield #4 // Field count:I
12: iconst_1
13: iadd
14: putfield #4 // Field count:I
17: aload_1
18: monitorexit
19: goto 27
22: astore_2
23: aload_1
24: monitorexit
25: aload_2
26: athrow
27: return
Exception table:
from to target type
7 19 22 any
22 25 22 any
LineNumberTable:
........