1 同步鎖synchronized追本溯源
引言
提到synchronized,無論是在開發程序中和面試程序中常常遇到的問題
synchronized;也算是重災區了
為什么說是重災區?
因為他不像其他的代碼,是有原始碼,可以查看的
synchronized是一個關鍵字,直接是找不到源代碼的
接下來
我們會通過java記憶體指令碼和c++原始碼(HotSpot虛擬機原始碼)
給大家剖析一下synchronized到底是怎么實作鎖同步的
1.1 synchronized場景回顧
目標:
synchronized回顧
概念
synchronized:是Java中的關鍵字,是一種同步鎖,
syn屬于哪種鎖分類:
-
樂觀鎖、悲觀鎖(syn)
-
獨享鎖(syn)、共享鎖
-
公平鎖、非公平鎖(syn)
-
互斥鎖(syn)、讀寫鎖
-
可重入鎖(syn)
tips:
synchronized JDK1.6鎖升級 : 無鎖 -> 偏向鎖 (非鎖)-> 輕量級鎖 -> 重量級鎖(1.6前都是)
多執行緒特性回顧(面試常問)
原子性:指一個操作或者多個操作,要么全部執行并且執行的程序不會被任何因素打斷,要么就都不執行
可見性:是指多個執行緒訪問一個資源時,該資源的狀態、值資訊等對于其他執行緒都是可見的,
有序性:指程式中代碼的執行順序 (編譯器會重排)
sync可以完整實作以上三個特性來保障執行緒安全性,cas就無法達到原子性,
這是什么原理呢?
1.2 反匯編尋找鎖實作原理
目標
通過javap反匯編看一下synchronized到底是怎么加鎖的
com.syn.BTest
public class BTest {
private static Object object = new Object();
public synchronized void testMethod() {
System.out.println("Hello World -synchronized method ");
}
public static void main(String[] args) {
synchronized (object) {
System.out.println("Hello World -synchronized block ");
}
}
}
反匯編后,我們將看到什么?

JDK自帶的一個工具: javap ,對位元組碼進行反匯編:
//com.syn.BTest
javap -v -c BTest.class
-v:輸出附加資訊
-c:對代碼進行反匯編
反匯編后

解釋
被synchronized修飾的代碼塊,多了兩個指令
monitorenter、monitorexit
即JVM使用monitorenter和monitorexit兩個指令實作同步

解釋
方法呼叫時會檢查方法的 ACC_SYNCHRONIZED 訪問標志是否被設定,如果設定了,執行執行緒將先獲取monitor,獲取成功之后才能執行方法體,方法執行完后再釋放monitor,也就是jvm會隱式呼叫monitorenter和
monitorexit,
- monitorenter原理
monitorenter首先我們來看一下JVM規范中對于monitorenter的描述
https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.monitorenter
monitorenter :
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.
monitorexit:
The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
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.
翻譯如下:
- monitorenter
每一個物件都會和一個監視器monitor關聯,
監視器被占用時會被鎖住,其他執行緒無法來獲取該monitor,
當JVM執行某個執行緒的某個方法內部的monitorenter時,它會嘗試去獲取當前物件對應
的monitor的所有權,其程序如下:
-
若monior的進入數為0,執行緒可以進入monitor,并將monitor的進入數置為1,當前執行緒成為
monitor的owner(所有者) -
若執行緒已擁有monitor的所有權,允許它重入monitor,則進入monitor的進入數加1
-
若其他執行緒已經占有monitor的所有權,那么當前嘗試獲取monitor的所有權的執行緒會被阻塞,直
到monitor的進入數變為0,才能重新嘗試獲取monitor的所有權,
- monitorexit
-
能執行monitorexit指令的執行緒一定是擁有當前物件的monitor的所有權的執行緒,
-
執行monitorexit時會將monitor的進入數減1,當monitor的進入數減為0時,當前執行緒退出
monitor,不再擁有monitor的所有權,此時其他被這個monitor阻塞的執行緒可以嘗試去獲取這個
monitor的所有權
monitorexit釋放鎖,
monitorexit插入在方法結束處和例外處,JVM保證每個monitorenter必須有對應的monitorexit,
tips(重要)
簡單的理解,monitor就是jvm底層的c++代碼中的一個物件ObjectMonitor,
這個物件里有個計數器,來記錄當前物件鎖有沒有人用,用了多少次,
以及一些佇列,存放調度一些需要這把鎖的執行緒,
關于monitor在c++里的結構,我們下文再詳細說,
總結:
1、synchronized是靠ObjectMonitor來控制鎖的
2、需要這把鎖的執行緒在monitor的佇列里被各種安排
3、拿到鎖的執行緒被monitor標記,計數加加,釋放鎖,需要將計數器減減操作
1.3 Monitor詳解
目標:Monitor的位置

接下來我們看它的詳細內部結構,以及如何運作的,
1.3.1 Monitor是什么
目標: 通過JVM虛擬機原始碼分析synchronized監視器Monitor到底是什么
tips:
c++原始碼了解即可,原理要明白
面試時很重要,面試過去了就不重要!(瞎說什么大實話)
在HotSpot虛擬機中,monitor監視器是由ObjectMonitor實作的,
構造器代碼src/share/vm/runtime/objectMonitor.hpp
hpp可以include包含cpp的東西,兩者都是c++的代碼
//構造器
ObjectMonitor() {
_header = NULL;
_count = 0;
_waiters = 0,
_recursions = 0; // 執行緒的重入次數
_object = NULL;
_owner = NULL; // 當前執行緒,拿到鎖的那位
_WaitSet = NULL; // 等待佇列,調wait的執行緒在這里
_WaitSetLock = 0 ;
_Responsible = NULL;
_succ = NULL;
_cxq = NULL; // 競爭佇列,掙不到鎖先進這里(可自旋)
FreeNext = NULL;
_EntryList = NULL; // 阻塞佇列,來自cxq(調unlock時)或者waitSet(調notify時)
_SpinFreq = 0;
_SpinClock = 0;
OwnerIsThread = 0;
}
留心這三個串列:
1)cxq(競爭串列)
cxq是一個單向鏈表,被掛起執行緒等待重新競爭鎖的鏈表, monitor 通過CAS將包裝成ObjectWaiter寫入到串列的頭部,為了避免插入和取出元素的競爭,所以Owner會從串列尾部取元素,所以這個東西可以理解為一上來競爭沒拿到鎖的在這里臨時待一會(1級快取),
2)EntryList(鎖候選者串列)
EntryList是一個雙向鏈表,當EntryList為空,cxq不為空,Owener會在unlock時,將cxq中的資料移動到EntryList,并指定EntryList串列頭的第一個執行緒為OnDeck執行緒,其他執行緒就待在里面,所以這個東西可以認為是二次競爭鎖還沒拿到的(里面有一個馬上就會拿到),(2級快取)
備注:EntryList跟cxq的區別
在cxq中的佇列可以繼續自旋等待鎖,若達到自旋的閾值仍未獲取到鎖則會呼叫park方法掛起,而EntryList中的執行緒都是被掛起的執行緒,
3)WaitList
WatiList是Owner執行緒地呼叫wait()方法后進入的執行緒,進入WaitList中的執行緒在notify()/notifyAll()呼叫后會被加入到EntryList,
程序總結:
- 等待鎖的執行緒會待在_cxq和entry set佇列中,具體哪個和當前執行緒取鎖的情況有關
- entry set的表頭執行緒獲取到物件的monitor后進入_Owner區域并把monitor中的
_owner變數設定為自己,同時monitor中的計數器_count加1 - 若執行緒呼叫
wait()方法,將釋放當前持有的monitor,_owner變數恢復為null,_count自減1,同時該執行緒進入_WaitSet集合中等待被喚醒, - 若當前執行緒執行完畢也將釋放monitor(鎖)并復位變數的值,以便其他執行緒進入獲取monitor(鎖),
1.3.2 詳細流程圖(了解)
monitorenter
monitorenter指令執行位置:
JVM原始碼:src/share/vm/interpreter/interpreterRuntime.cpp
JVM函式入口:InterpreterRuntime::monitorenter
最終呼叫:src/share/vm/runtime/objectMonitor.cpp中的 ObjectMonitor::enter

monitorexit
執行monitorexit指令位置:
代碼檔案:src/share/vm/runtime/objectMonitor.cpp
呼叫函式:ObjectMonitor::exit

本文由傳智教育博學谷 - 狂野架構師教研團隊發布
如果本文對您有幫助,歡迎關注和點贊;如果您有任何建議也可留言評論或私信,您的支持是我堅持創作的動力
轉載請注明出處!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/501326.html
標籤:其他
下一篇:面向物件ooDay8
