国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

(六) synchronized的源碼分析

jhhfft / 2335人閱讀

摘要:關鍵字經過編譯之后,會在同步塊的前后分別形成和這兩個字節碼指令。當我們的把字節碼加載到內存的時候,會對這兩個指令進行解析。這兩個字節碼都需要一個類型的參數來指明要鎖定和解鎖的對象。最后喚醒暫停的線程。

文章簡介

前面我有文章介紹了synchronized的基本原理,這篇文章我會從jvm源碼分析synchronized的實現邏輯,希望讓大家有一個更加深度的認識

內容導航

從synchronized的字節碼說起

什么是monitor

分析synchronized的源碼

從synchronized的字節碼說起

由于synchronized的實現是在jvm層面,所以我們如果要看它的源碼,需要從字節碼入手。這段代碼演示了synchronized作為實例鎖的兩種用法,我們觀察一下這段代碼生成的字節碼

</>復制代碼

  1. public class App
  2. {
  3. public synchronized void test1(){
  4. }
  5. public void test2(){
  6. synchronized (this){
  7. }
  8. }
  9. public static void main( String[] args ){
  10. System.out.println( "Hello World!" );
  11. }
  12. }

</>復制代碼

  1. 進入classpath目錄下找到App.class文件, 在cmd中輸入 javap -v App.class查看字節碼

</>復制代碼

  1. public synchronized void test1();
  2. descriptor: ()V
  3. flags: ACC_PUBLIC, ACC_SYNCHRONIZED
  4. Code:
  5. stack=0, locals=1, args_size=1
  6. 0: return
  7. LineNumberTable:
  8. line 10: 0
  9. LocalVariableTable:
  10. Start Length Slot Name Signature
  11. 0 1 0 this Lcom/gupaoedu/openclass/App;
  12. public void test2();
  13. descriptor: ()V
  14. flags: ACC_PUBLIC
  15. Code:
  16. stack=2, locals=3, args_size=1
  17. 0: aload_0
  18. 1: dup
  19. 2: astore_1
  20. 3: monitorenter //監視器進入,獲取鎖
  21. 4: aload_1
  22. 5: monitorexit //監視器退出,釋放鎖
  23. 6: goto 14
  24. 9: astore_2
  25. 10: aload_1
  26. 11: monitorexit
  27. 12: aload_2
  28. 13: athrow
  29. 14: return

通過字節碼我們可以發現,修飾在方法層面的同步關鍵字,會多一個 ACC_SYNCHRONIZED的flag;修飾在代碼塊層面的同步塊會多一個 monitorenter和 monitorexit關鍵字。無論采用哪一種方式,本質上都是對一個對象的監視器(monitor)進行獲取,而這個獲取的過程是排他的,也就是同一個時刻只能有一個線程獲得同步塊對象的監視器。
在 synchronized的原理分析這篇文章中,有提到對象監視器。

</>復制代碼

  1. synchronized關鍵字經過編譯之后,會在同步塊的前后分別形成monitorenter和monitorexit這兩個字節碼指令。當我們的JVM把字節碼加載到內存的時候,會對這兩個指令進行解析。這兩個字節碼都需要一個Object類型的參數來指明要鎖定和解鎖的對象。如果Java程序中的synchronized明確指定了對象參數,那么這個對象就是加鎖和解鎖的對象;如果沒有明確指定,那就根據synchronized修飾的是實例方法還是類方法,獲取對應的對象實例或Class對象來作為鎖對象
什么是monitor

在分析源代碼之前需要了解oop, oopDesc, markOop等相關概念,在Synchronized的原理分析這篇文章中,我們講到了synchronized的同步鎖實際上是存儲在對象頭中,這個對象頭是一個Java對象在內存中的布局的一部分。Java中的每一個Object在JVM內部都會有一個native的C++對象oop/oopDesc與之對應。在hotspot源碼 oop.hpp中oopDesc的定義如下

</>復制代碼

  1. class oopDesc {
  2. friend class VMStructs;
  3. private:
  4. volatile markOop _mark;
  5. union _metadata {
  6. Klass* _klass;
  7. narrowKlass _compressed_klass;
  8. } _metadata;

其中 markOop就是我們所說的Mark Word,用于存儲鎖的標識。
hotspot源碼 markOop.hpp文件代碼片段

</>復制代碼

  1. class markOopDesc: public oopDesc {
  2. private:
  3. // Conversion
  4. uintptr_t value() const { return (uintptr_t) this; }
  5. public:
  6. // Constants
  7. enum { age_bits = 4,
  8. lock_bits = 2,
  9. biased_lock_bits = 1,
  10. max_hash_bits = BitsPerWord - age_bits - lock_bits - biased_lock_bits,
  11. hash_bits = max_hash_bits > 31 ? 31 : max_hash_bits,
  12. cms_bits = LP64_ONLY(1) NOT_LP64(0),
  13. epoch_bits = 2
  14. };
  15. ...
  16. }

markOopDesc繼承自oopDesc,并且擴展了自己的monitor方法,這個方法返回一個ObjectMonitor指針對象,在hotspot虛擬機中,采用ObjectMonitor類來實現monitor

</>復制代碼

  1. bool has_monitor() const {
  2. return ((value() & monitor_value) != 0);
  3. }
  4. ObjectMonitor* monitor() const {
  5. assert(has_monitor(), "check");
  6. // Use xor instead of &~ to provide one extra tag-bit check.
  7. return (ObjectMonitor*) (value() ^ monitor_value);
  8. }

在 ObjectMonitor.hpp中,可以看到ObjectMonitor的定義

</>復制代碼

  1. class ObjectMonitor {
  2. ...
  3. ObjectMonitor() {
  4. _header = NULL; //markOop對象頭
  5. _count = 0;
  6. _waiters = 0, //等待線程數
  7. _recursions = 0; //重入次數
  8. _object = NULL;
  9. _owner = NULL; //獲得ObjectMonitor對象的線程
  10. _WaitSet = NULL; //處于wait狀態的線程,會被加入到waitSet
  11. _WaitSetLock = 0 ;
  12. _Responsible = NULL ;
  13. _succ = NULL ;
  14. _cxq = NULL ;
  15. FreeNext = NULL ;
  16. _EntryList = NULL ; //處于等待鎖BLOCKED狀態的線程
  17. _SpinFreq = 0 ;
  18. _SpinClock = 0 ;
  19. OwnerIsThread = 0 ;
  20. _previous_owner_tid = 0; //監視器前一個擁有線程的ID
  21. }
  22. ...

簡單總結一下,同步塊的實現使用 monitorenter和 monitorexit指令,而同步方法是依靠方法修飾符上的flag ACC_SYNCHRONIZED來完成。其本質是對一個對象監視器(monitor)進行獲取,這個獲取過程是排他的,也就是同一個時刻只能有一個線程獲得由synchronized所保護對象的監視器。所謂的監視器,實際上可以理解為一個同步工具,它是由Java對象進行描述的。在Hotspot中,是通過ObjectMonitor來實現,每個對象中都會內置一個ObjectMonitor對象

簡單分析synchronized的源碼

從 monitorenter和 monitorexit這兩個指令來開始閱讀源碼,JVM將字節碼加載到內存以后,會對這兩個指令進行解釋執行, monitorenter, monitorexit的指令解析是通過 InterpreterRuntime.cpp中的兩個方法實現

</>復制代碼

  1. InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem)
  2. InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem)
  3. //JavaThread 當前獲取鎖的線程
  4. //BasicObjectLock 基礎對象鎖

我們基于monitorenter為入口,沿著偏向鎖->輕量級鎖->重量級鎖的路徑來分析synchronized的實現過程

</>復制代碼

  1. IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
  2. #ifdef ASSERT
  3. thread->last_frame().interpreter_frame_verify_monitor(elem);
  4. #endif
  5. ...
  6. if (UseBiasedLocking) {
  7. // Retry fast entry if bias is revoked to avoid unnecessary inflation
  8. ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
  9. } else {
  10. ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
  11. }
  12. ...
  13. #ifdef ASSERT
  14. thread->last_frame().interpreter_frame_verify_monitor(elem);
  15. #endif
  16. IRT_END

UseBiasedLocking是在JVM啟動的時候,是否啟動偏向鎖的標識

如果支持偏向鎖,則執行 ObjectSynchronizer::fast_enter的邏輯

如果不支持偏向鎖,則執行 ObjectSynchronizer::slow_enter邏輯,繞過偏向鎖,直接進入輕量級鎖

ObjectSynchronizer::fast_enter的實現在 synchronizer.cpp文件中,代碼如下

</>復制代碼

  1. void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, bool attempt_rebias, TRAPS) {
  2. if (UseBiasedLocking) { //判斷是否開啟了偏向鎖
  3. if (!SafepointSynchronize::is_at_safepoint()) { //如果不處于全局安全點
  4. //通過`revoke_and_rebias`這個函數嘗試獲取偏向鎖
  5. BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD);
  6. if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) {//如果是撤銷與重偏向直接返回
  7. return;
  8. }
  9. } else {//如果在安全點,撤銷偏向鎖
  10. assert(!attempt_rebias, "can not rebias toward VM thread");
  11. BiasedLocking::revoke_at_safepoint(obj);
  12. }
  13. assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
  14. }
  15. slow_enter (obj, lock, THREAD) ;
  16. }

fast_enter方法的主要流程做一個簡單的解釋

再次檢查偏向鎖是否開啟

當處于不安全點時,通過 revoke_and_rebias嘗試獲取偏向鎖,如果成功則直接返回,如果失敗則進入輕量級鎖獲取過程

revoke_and_rebias這個偏向鎖的獲取邏輯在 biasedLocking.cpp中

如果偏向鎖未開啟,則進入 slow_enter獲取輕量級鎖的流程

偏向鎖的獲取邏輯

BiasedLocking::revoke_and_rebias 是用來獲取當前偏向鎖的狀態(可能是偏向鎖撤銷后重新偏向)。這個方法的邏輯在 biasedLocking.cpp中

</>復制代碼

  1. BiasedLocking::Condition BiasedLocking::revoke_and_rebias(Handle obj, bool attempt_rebias, TRAPS) {
  2. assert(!SafepointSynchronize::is_at_safepoint(), "must not be called while at safepoint");
  3. markOop mark = obj->mark(); //獲取鎖對象的對象頭
  4. //判斷mark是否為可偏向狀態,即mark的偏向鎖標志位為1,鎖標志位為 01,線程id為null
  5. if (mark->is_biased_anonymously() && !attempt_rebias) {
  6. //這個分支是進行對象的hashCode計算時會進入,在一個非全局安全點進行偏向鎖撤銷
  7. markOop biased_value = mark;
  8. //創建一個非偏向的markword
  9. markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
  10. //Atomic:cmpxchg_ptr是CAS操作,通過cas重新設置偏向鎖狀態
  11. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(unbiased_prototype, obj->mark_addr(), mark);
  12. if (res_mark == biased_value) {//如果CAS成功,返回偏向鎖撤銷狀態
  13. return BIAS_REVOKED;
  14. }
  15. } else if (mark->has_bias_pattern()) {//如果鎖對象為可偏向狀態(biased_lock:1, lock:01,不管線程id是否為空),嘗試重新偏向
  16. Klass* k = obj->klass();
  17. markOop prototype_header = k->prototype_header();
  18. //如果已經有線程對鎖對象進行了全局鎖定,則取消偏向鎖操作
  19. if (!prototype_header->has_bias_pattern()) {
  20. markOop biased_value = mark;
  21. //CAS 更新對象頭markword為非偏向鎖
  22. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(prototype_header, obj->mark_addr(), mark);
  23. assert(!(*(obj->mark_addr()))->has_bias_pattern(), "even if we raced, should still be revoked");
  24. return BIAS_REVOKED; //返回偏向鎖撤銷狀態
  25. } else if (prototype_header->bias_epoch() != mark->bias_epoch()) {
  26. //如果偏向鎖過期,則進入當前分支
  27. if (attempt_rebias) {//如果允許嘗試獲取偏向鎖
  28. assert(THREAD->is_Java_thread(), "");
  29. markOop biased_value = mark;
  30. markOop rebiased_prototype = markOopDesc::encode((JavaThread*) THREAD, mark->age(), prototype_header->bias_epoch());
  31. //通過CAS 操作, 將本線程的 ThreadID 、時間錯、分代年齡嘗試寫入對象頭中
  32. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(rebiased_prototype, obj->mark_addr(), mark);
  33. if (res_mark == biased_value) { //CAS成功,則返回撤銷和重新偏向狀態
  34. return BIAS_REVOKED_AND_REBIASED;
  35. }
  36. } else {//不嘗試獲取偏向鎖,則取消偏向鎖
  37. //通過CAS操作更新分代年齡
  38. markOop biased_value = mark;
  39. markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
  40. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(unbiased_prototype, obj->mark_addr(), mark);
  41. if (res_mark == biased_value) { //如果CAS操作成功,返回偏向鎖撤銷狀態
  42. return BIAS_REVOKED;
  43. }
  44. }
  45. }
  46. }
  47. ...//省略
  48. }
偏向鎖的撤銷

當到達一個全局安全點時,這時會根據偏向鎖的狀態來判斷是否需要撤銷偏向鎖,調用 revoke_at_safepoint方法,這個方法也是在 biasedLocking.cpp中定義的

</>復制代碼

  1. void BiasedLocking::revoke_at_safepoint(Handle h_obj) {
  2. assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint");
  3. oop obj = h_obj();
  4. //更新撤銷偏向鎖計數,并返回偏向鎖撤銷次數和偏向次數
  5. HeuristicsResult heuristics = update_heuristics(obj, false);
  6. if (heuristics == HR_SINGLE_REVOKE) {//可偏向且未達到批量處理的閾值(下面會多帶帶解釋)
  7. revoke_bias(obj, false, false, NULL); //撤銷偏向鎖
  8. } else if ((heuristics == HR_BULK_REBIAS) ||
  9. (heuristics == HR_BULK_REVOKE)) {//如果是多次撤銷或者多次偏向
  10. //批量撤銷
  11. bulk_revoke_or_rebias_at_safepoint(obj, (heuristics == HR_BULK_REBIAS), false, NULL);
  12. }
  13. clean_up_cached_monitor_info();
  14. }

偏向鎖的釋放,需要等待全局安全點(在這個時間點上沒有正在執行的字節碼),首先暫停擁有偏向鎖的線程,然后檢查持有偏向鎖的線程是否還活著,如果線程不處于活動狀態,則將對象頭設置成無鎖狀態。如果線程仍然活著,則會升級為輕量級鎖,遍歷偏向對象的所記錄。棧幀中的鎖記錄和對象頭的Mark Word要么重新偏向其他線程,要么恢復到無鎖,或者標記對象不適合作為偏向鎖。最后喚醒暫停的線程。

</>復制代碼

  1. JVM內部為每個類維護了一個偏向鎖revoke計數器,對偏向鎖撤銷進行計數,當這個值達到指定閾值時,JVM會認為這個類的偏向鎖有問題,需要重新偏向(rebias),對所有屬于這個類的對象進行重偏向的操作成為 批量重偏向(bulk rebias)。在做bulk rebias時,會對這個類的epoch的值做遞增,這個epoch會存儲在對象頭中的epoch字段。在判斷這個對象是否獲得偏向鎖的條件是:markword的 biased_lock:1lock:01、threadid和當前線程id相等、epoch字段和所屬類的epoch值相同,如果epoch的值不一樣,要么就是撤銷偏向鎖、要么就是rebias; 如果這個類的revoke計數器的值繼續增加到一個閾值,那么jvm會認為這個類不適合偏向鎖,就需要進行bulk revoke操作
輕量級鎖的獲取邏輯

輕量級鎖的獲取,是調用 ::slow_enter方法,該方法同樣位于 synchronizer.cpp文件中

</>復制代碼

  1. void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
  2. markOop mark = obj->mark();
  3. assert(!mark->has_bias_pattern(), "should not see bias pattern here");
  4. if (mark->is_neutral()) { //如果當前是無鎖狀態, markword的biase_lock:0,lock:01
  5. //直接把mark保存到BasicLock對象的_displaced_header字段
  6. lock->set_displaced_header(mark);
  7. //通過CAS將mark word更新為指向BasicLock對象的指針,更新成功表示獲得了輕量級鎖
  8. if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) {
  9. TEVENT (slow_enter: release stacklock) ;
  10. return ;
  11. }
  12. // Fall through to inflate() ...
  13. }
  14. //如果markword處于加鎖狀態、且markword中的ptr指針指向當前線程的棧幀,表示為重入操作,不需要爭搶鎖
  15. else if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
  16. assert(lock != mark->locker(), "must not re-lock the same lock");
  17. assert(lock != (BasicLock*)obj->mark(), "don"t relock with same BasicLock");
  18. lock->set_displaced_header(NULL);
  19. return;
  20. }
  21. #if 0
  22. // The following optimization isn"t particularly useful.
  23. if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) {
  24. lock->set_displaced_header (NULL) ;
  25. return ;
  26. }
  27. #endif
  28. //代碼執行到這里,說明有多個線程競爭輕量級鎖,輕量級鎖通過`inflate`進行膨脹升級為重量級鎖
  29. lock->set_displaced_header(markOopDesc::unused_mark());
  30. ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
  31. }

輕量級鎖的獲取邏輯簡單再整理一下

mark->is_neutral()方法, is_neutral這個方法是在 markOop.hpp中定義,如果 biased_lock:0且lock:01表示無鎖狀態

如果mark處于無鎖狀態,則進入步驟(3),否則執行步驟(5)

把mark保存到BasicLock對象的displacedheader字段

通過CAS嘗試將markword更新為指向BasicLock對象的指針,如果更新成功,表示競爭到鎖,則執行同步代碼,否則執行步驟(5)

如果當前mark處于加鎖狀態,且mark中的ptr指針指向當前線程的棧幀,則執行同步代碼,否則說明有多個線程競爭輕量級鎖,輕量級鎖需要膨脹升級為重量級鎖

輕量級鎖的釋放邏輯

輕量級鎖的釋放是通過 monitorexit調用

</>復制代碼

  1. IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
  2. #ifdef ASSERT
  3. thread->last_frame().interpreter_frame_verify_monitor(elem);
  4. #endif
  5. Handle h_obj(thread, elem->obj());
  6. assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
  7. "must be NULL or an object");
  8. if (elem == NULL || h_obj()->is_unlocked()) {
  9. THROW(vmSymbols::java_lang_IllegalMonitorStateException());
  10. }
  11. ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
  12. // Free entry. This must be done here, since a pending exception might be installed on
  13. // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
  14. elem->set_obj(NULL);
  15. #ifdef ASSERT
  16. thread->last_frame().interpreter_frame_verify_monitor(elem);
  17. #endif
  18. IRT_END

這段代碼中主要是通過 ObjectSynchronizer::slow_exit來執行

</>復制代碼

  1. void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
  2. fast_exit (object, lock, THREAD) ;
  3. }

ObjectSynchronizer::fast_exit的代碼如下

</>復制代碼

  1. void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) {
  2. assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here");
  3. // if displaced header is null, the previous enter is recursive enter, no-op
  4. markOop dhw = lock->displaced_header(); //獲取鎖對象中的對象頭
  5. markOop mark ;
  6. if (dhw == NULL) {
  7. // Recursive stack-lock.
  8. // Diagnostics -- Could be: stack-locked, inflating, inflated.
  9. mark = object->mark() ;
  10. assert (!mark->is_neutral(), "invariant") ;
  11. if (mark->has_locker() && mark != markOopDesc::INFLATING()) {
  12. assert(THREAD->is_lock_owned((address)mark->locker()), "invariant") ;
  13. }
  14. if (mark->has_monitor()) {
  15. ObjectMonitor * m = mark->monitor() ;
  16. assert(((oop)(m->object()))->mark() == mark, "invariant") ;
  17. assert(m->is_entered(THREAD), "invariant") ;
  18. }
  19. return ;
  20. }
  21. mark = object->mark() ; //獲取線程棧幀中鎖記錄(LockRecord)中的markword
  22. // If the object is stack-locked by the current thread, try to
  23. // swing the displaced header from the box back to the mark.
  24. if (mark == (markOop) lock) {
  25. assert (dhw->is_neutral(), "invariant") ;
  26. //通過CAS嘗試將Displaced Mark Word替換回對象頭,如果成功,表示鎖釋放成功。
  27. if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) {
  28. TEVENT (fast_exit: release stacklock) ;
  29. return;
  30. }
  31. }
  32. //鎖膨脹,調用重量級鎖的釋放鎖方法
  33. ObjectSynchronizer::inflate(THREAD, object)->exit (true, THREAD) ;
  34. }

輕量級鎖的釋放也比較簡單,就是將當前線程棧幀中鎖記錄空間中的Mark Word替換到鎖對象的對象頭中,如果成功表示鎖釋放成功。否則,鎖膨脹成重量級鎖,實現重量級鎖的釋放鎖邏輯

鎖膨脹的過程分析

重量級鎖是通過對象內部的監視器(monitor)來實現,而monitor的本質是依賴操作系統底層的MutexLock實現的。我們先來看鎖的膨脹過程,從前面的分析中已經知道了所膨脹的過程是通過 ObjectSynchronizer::inflate方法實現的,代碼如下

</>復制代碼

  1. ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
  2. // Inflate mutates the heap ...
  3. // Relaxing assertion for bug 6320749.
  4. assert (Universe::verify_in_progress() ||
  5. !SafepointSynchronize::is_at_safepoint(), "invariant") ;
  6. for (;;) { //通過無意義的循環實現自旋操作
  7. const markOop mark = object->mark() ;
  8. assert (!mark->has_bias_pattern(), "invariant") ;
  9. if (mark->has_monitor()) {//has_monitor是markOop.hpp中的方法,如果為true表示當前鎖已經是重量級鎖了
  10. ObjectMonitor * inf = mark->monitor() ;//獲得重量級鎖的對象監視器直接返回
  11. assert (inf->header()->is_neutral(), "invariant");
  12. assert (inf->object() == object, "invariant") ;
  13. assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
  14. return inf ;
  15. }
  16. if (mark == markOopDesc::INFLATING()) {//膨脹等待,表示存在線程正在膨脹,通過continue進行下一輪的膨脹
  17. TEVENT (Inflate: spin while INFLATING) ;
  18. ReadStableMark(object) ;
  19. continue ;
  20. }
  21. if (mark->has_locker()) {//表示當前鎖為輕量級鎖,以下是輕量級鎖的膨脹邏輯
  22. ObjectMonitor * m = omAlloc (Self) ;//獲取一個可用的ObjectMonitor
  23. // Optimistically prepare the objectmonitor - anticipate successful CAS
  24. // We do this before the CAS in order to minimize the length of time
  25. // in which INFLATING appears in the mark.
  26. m->Recycle();
  27. m->_Responsible = NULL ;
  28. m->OwnerIsThread = 0 ;
  29. m->_recursions = 0 ;
  30. m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // Consider: maintain by type/class
  31. /**將object->mark_addr()和mark比較,如果這兩個值相等,則將object->mark_addr()
  32. 改成markOopDesc::INFLATING(),相等返回是mark,不相等返回的是object->mark_addr()**/
  33. markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ;
  34. if (cmp != mark) {//CAS失敗
  35. omRelease (Self, m, true) ;//釋放監視器
  36. continue ; // 重試
  37. }
  38. markOop dmw = mark->displaced_mark_helper() ;
  39. assert (dmw->is_neutral(), "invariant") ;
  40. //CAS成功以后,設置ObjectMonitor相關屬性
  41. m->set_header(dmw) ;
  42. m->set_owner(mark->locker());
  43. m->set_object(object);
  44. // TODO-FIXME: assert BasicLock->dhw != 0.
  45. guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
  46. object->release_set_mark(markOopDesc::encode(m));
  47. if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
  48. TEVENT(Inflate: overwrite stacklock) ;
  49. if (TraceMonitorInflation) {
  50. if (object->is_instance()) {
  51. ResourceMark rm;
  52. tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  53. (void *) object, (intptr_t) object->mark(),
  54. object->klass()->external_name());
  55. }
  56. }
  57. return m ; //返回ObjectMonitor
  58. }
  59. //如果是無鎖狀態
  60. assert (mark->is_neutral(), "invariant");
  61. ObjectMonitor * m = omAlloc (Self) ; ////獲取一個可用的ObjectMonitor
  62. //設置ObjectMonitor相關屬性
  63. m->Recycle();
  64. m->set_header(mark);
  65. m->set_owner(NULL);
  66. m->set_object(object);
  67. m->OwnerIsThread = 1 ;
  68. m->_recursions = 0 ;
  69. m->_Responsible = NULL ;
  70. m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // consider: keep metastats by type/class
  71. /**將object->mark_addr()和mark比較,如果這兩個值相等,則將object->mark_addr()
  72. 改成markOopDesc::encode(m),相等返回是mark,不相等返回的是object->mark_addr()**/
  73. if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) {
  74. //CAS失敗,說明出現了鎖競爭,則釋放監視器重行競爭鎖
  75. m->set_object (NULL) ;
  76. m->set_owner (NULL) ;
  77. m->OwnerIsThread = 0 ;
  78. m->Recycle() ;
  79. omRelease (Self, m, true) ;
  80. m = NULL ;
  81. continue ;
  82. // interference - the markword changed - just retry.
  83. // The state-transitions are one-way, so there"s no chance of
  84. // live-lock -- "Inflated" is an absorbing state.
  85. }
  86. if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
  87. TEVENT(Inflate: overwrite neutral) ;
  88. if (TraceMonitorInflation) {
  89. if (object->is_instance()) {
  90. ResourceMark rm;
  91. tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  92. (void *) object, (intptr_t) object->mark(),
  93. object->klass()->external_name());
  94. }
  95. }
  96. return m ; //返回ObjectMonitor對象
  97. }
  98. }

鎖膨脹的過程稍微有點復雜,整個鎖膨脹的過程是通過自旋來完成的,具體的實現邏輯簡答總結以下幾點

mark->has_monitor() 判斷如果當前鎖對象為重量級鎖,也就是lock:10,則執行(2),否則執行(3)

通過 mark->monitor獲得重量級鎖的對象監視器ObjectMonitor并返回,鎖膨脹過程結束

如果當前鎖處于 INFLATING,說明有其他線程在執行鎖膨脹,那么當前線程通過自旋等待其他線程鎖膨脹完成

如果當前是輕量級鎖狀態 mark->has_locker(),則進行鎖膨脹。首先,通過omAlloc方法獲得一個可用的ObjectMonitor,并設置初始數據;然后通過CAS將對象頭設置為`markOopDesc:INFLATING,表示當前鎖正在膨脹,如果CAS失敗,繼續自旋

如果是無鎖狀態,邏輯類似第4步驟

</>復制代碼

  1. 鎖膨脹的過程實際上是獲得一個ObjectMonitor對象監視器,而真正搶占鎖的邏輯,在 ObjectMonitor::enter方法里面
重量級鎖的競爭邏輯

重量級鎖的競爭,在 ObjectMonitor::enter方法中,代碼文件在 objectMonitor.cpp重量級鎖的代碼就不一一分析了,簡單說一下下面這段代碼主要做的幾件事

通過CAS將monitor的 _owner字段設置為當前線程,如果設置成功,則直接返回

如果之前的 _owner指向的是當前的線程,說明是重入,執行 _recursions++增加重入次數

如果當前線程獲取監視器鎖成功,將 _recursions設置為1, _owner設置為當前線程

如果獲取鎖失敗,則等待鎖釋放

</>復制代碼

  1. void ATTR ObjectMonitor::enter(TRAPS) {
  2. // The following code is ordered to check the most common cases first
  3. // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors.
  4. Thread * const Self = THREAD ;
  5. void * cur ;
  6. cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL) ;
  7. if (cur == NULL) {//CAS成功
  8. // Either ASSERT _recursions == 0 or explicitly set _recursions = 0.
  9. assert (_recursions == 0 , "invariant") ;
  10. assert (_owner == Self, "invariant") ;
  11. // CONSIDER: set or assert OwnerIsThread == 1
  12. return ;
  13. }
  14. if (cur == Self) {
  15. // TODO-FIXME: check for integer overflow! BUGID 6557169.
  16. _recursions ++ ;
  17. return ;
  18. }
  19. if (Self->is_lock_owned ((address)cur)) {
  20. assert (_recursions == 0, "internal state error");
  21. _recursions = 1 ;
  22. // Commute owner from a thread-specific on-stack BasicLockObject address to
  23. // a full-fledged "Thread *".
  24. _owner = Self ;
  25. OwnerIsThread = 1 ;
  26. return ;
  27. }
  28. // We"ve encountered genuine contention.
  29. assert (Self->_Stalled == 0, "invariant") ;
  30. Self->_Stalled = intptr_t(this) ;
  31. // Try one round of spinning *before* enqueueing Self
  32. // and before going through the awkward and expensive state
  33. // transitions. The following spin is strictly optional ...
  34. // Note that if we acquire the monitor from an initial spin
  35. // we forgo posting JVMTI events and firing DTRACE probes.
  36. if (Knob_SpinEarly && TrySpin (Self) > 0) {
  37. assert (_owner == Self , "invariant") ;
  38. assert (_recursions == 0 , "invariant") ;
  39. assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
  40. Self->_Stalled = 0 ;
  41. return ;
  42. }
  43. assert (_owner != Self , "invariant") ;
  44. assert (_succ != Self , "invariant") ;
  45. assert (Self->is_Java_thread() , "invariant") ;
  46. JavaThread * jt = (JavaThread *) Self ;
  47. assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
  48. assert (jt->thread_state() != _thread_blocked , "invariant") ;
  49. assert (this->object() != NULL , "invariant") ;
  50. assert (_count >= 0, "invariant") ;
  51. // Prevent deflation at STW-time. See deflate_idle_monitors() and is_busy().
  52. // Ensure the object-monitor relationship remains stable while there"s contention.
  53. Atomic::inc_ptr(&_count);
  54. EventJavaMonitorEnter event;
  55. { // Change java thread status to indicate blocked on monitor enter.
  56. JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this);
  57. DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt);
  58. if (JvmtiExport::should_post_monitor_contended_enter()) {
  59. JvmtiExport::post_monitor_contended_enter(jt, this);
  60. }
  61. OSThreadContendState osts(Self->osthread());
  62. ThreadBlockInVM tbivm(jt);
  63. Self->set_current_pending_monitor(this);
  64. // TODO-FIXME: change the following for(;;) loop to straight-line code.
  65. for (;;) {
  66. jt->set_suspend_equivalent();
  67. // cleared by handle_special_suspend_equivalent_condition()
  68. // or java_suspend_self()
  69. EnterI (THREAD) ;
  70. if (!ExitSuspendEquivalent(jt)) break ;
  71. //
  72. // We have acquired the contended monitor, but while we were
  73. // waiting another thread suspended us. We don"t want to enter
  74. // the monitor while suspended because that would surprise the
  75. // thread that suspended us.
  76. //
  77. _recursions = 0 ;
  78. _succ = NULL ;
  79. exit (false, Self) ;
  80. jt->java_suspend_self();
  81. }
  82. Self->set_current_pending_monitor(NULL);
  83. }
  84. ...//此處省略無數行代碼

如果獲取鎖失敗,則需要通過自旋的方式等待鎖釋放,自旋執行的方法是 ObjectMonitor::EnterI,部分代碼如下

將當前線程封裝成ObjectWaiter對象node,狀態設置成TS_CXQ

通過自旋操作將node節點push到_cxq隊列

node節點添加到_cxq隊列之后,繼續通過自旋嘗試獲取鎖,如果在指定的閾值范圍內沒有獲得鎖,則通過park將當前線程掛起,等待被喚醒

</>復制代碼

  1. void ATTR ObjectMonitor::EnterI (TRAPS) {
  2. Thread * Self = THREAD ;
  3. ...//省略很多代碼
  4. ObjectWaiter node(Self) ;
  5. Self->_ParkEvent->reset() ;
  6. node._prev = (ObjectWaiter *) 0xBAD ;
  7. node.TState = ObjectWaiter::TS_CXQ ;
  8. // Push "Self" onto the front of the _cxq.
  9. // Once on cxq/EntryList, Self stays on-queue until it acquires the lock.
  10. // Note that spinning tends to reduce the rate at which threads
  11. // enqueue and dequeue on EntryList|cxq.
  12. ObjectWaiter * nxt ;
  13. for (;;) { //自旋,講node添加到_cxq隊列
  14. node._next = nxt = _cxq ;
  15. if (Atomic::cmpxchg_ptr (&node, &_cxq, nxt) == nxt) break ;
  16. // Interference - the CAS failed because _cxq changed. Just retry.
  17. // As an optional optimization we retry the lock.
  18. if (TryLock (Self) > 0) {
  19. assert (_succ != Self , "invariant") ;
  20. assert (_owner == Self , "invariant") ;
  21. assert (_Responsible != Self , "invariant") ;
  22. return ;
  23. }
  24. }
  25. ...//省略很多代碼
  26. //node節點添加到_cxq隊列之后,繼續通過自旋嘗試獲取鎖,如果在指定的閾值范圍內沒有獲得鎖,則通過park將當前線程掛起,等待被喚醒
  27. for (;;) {
  28. if (TryLock (Self) > 0) break ;
  29. assert (_owner != Self, "invariant") ;
  30. if ((SyncFlags & 2) && _Responsible == NULL) {
  31. Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ;
  32. }
  33. // park self //通過park掛起當前線程
  34. if (_Responsible == Self || (SyncFlags & 1)) {
  35. TEVENT (Inflated enter - park TIMED) ;
  36. Self->_ParkEvent->park ((jlong) RecheckInterval) ;
  37. // Increase the RecheckInterval, but clamp the value.
  38. RecheckInterval *= 8 ;
  39. if (RecheckInterval > 1000) RecheckInterval = 1000 ;
  40. } else {
  41. TEVENT (Inflated enter - park UNTIMED) ;
  42. Self->_ParkEvent->park() ;//當前線程掛起
  43. }
  44. if (TryLock(Self) > 0) break ; //當線程被喚醒時,會從這里繼續執行
  45. TEVENT (Inflated enter - Futile wakeup) ;
  46. if (ObjectMonitor::_sync_FutileWakeups != NULL) {
  47. ObjectMonitor::_sync_FutileWakeups->inc() ;
  48. }
  49. ++ nWakeups ;
  50. if ((Knob_SpinAfterFutile & 1) && TrySpin (Self) > 0) break ;
  51. if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) {
  52. Self->_ParkEvent->reset() ;
  53. OrderAccess::fence() ;
  54. }
  55. if (_succ == Self) _succ = NULL ;
  56. // Invariant: after clearing _succ a thread *must* retry _owner before parking.
  57. OrderAccess::fence() ;
  58. }
  59. ...//省略很多代碼
  60. }

TryLock(self)的代碼是在 ObjectMonitor::TryLock定義的,代碼的實現如下

</>復制代碼

  1. 代碼的實現原理很簡單,通過自旋,CAS設置monitor的_owner字段為當前線程,如果成功,表示獲取到了鎖,如果失敗,則繼續被掛起

</>復制代碼

  1. int ObjectMonitor::TryLock (Thread * Self) {
  2. for (;;) {
  3. void * own = _owner ;
  4. if (own != NULL) return 0 ;
  5. if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
  6. // Either guarantee _recursions == 0 or set _recursions = 0.
  7. assert (_recursions == 0, "invariant") ;
  8. assert (_owner == Self, "invariant") ;
  9. // CONSIDER: set or assert that OwnerIsThread == 1
  10. return 1 ;
  11. }
  12. // The lock had been free momentarily, but we lost the race to the lock.
  13. // Interference -- the CAS failed.
  14. // We can either return -1 or retry.
  15. // Retry doesn"t make as much sense because the lock was just acquired.
  16. if (true) return -1 ;
  17. }
  18. }
重量級鎖的釋放

重量級鎖的釋放是通過 ObjectMonitor::exit來實現的,釋放以后會通知被阻塞的線程去競爭鎖

判斷當前鎖對象中的owner沒有指向當前線程,如果owner指向的BasicLock在當前線程棧上,那么將_owner指向當前線程

如果當前鎖對象中的_owner指向當前線程,則判斷當前線程重入鎖的次數,如果不為0,繼續執行ObjectMonitor::exit(),直到重入鎖次數為0為止

釋放當前鎖,并根據QMode的模式判斷,是否將_cxq中掛起的線程喚醒。還是其他操作

</>復制代碼

  1. void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) {
  2. Thread * Self = THREAD ;
  3. if (THREAD != _owner) {//如果當前鎖對象中的_owner沒有指向當前線程
  4. //如果_owner指向的BasicLock在當前線程棧上,那么將_owner指向當前線程
  5. if (THREAD->is_lock_owned((address) _owner)) {
  6. // Transmute _owner from a BasicLock pointer to a Thread address.
  7. // We don"t need to hold _mutex for this transition.
  8. // Non-null to Non-null is safe as long as all readers can
  9. // tolerate either flavor.
  10. assert (_recursions == 0, "invariant") ;
  11. _owner = THREAD ;
  12. _recursions = 0 ;
  13. OwnerIsThread = 1 ;
  14. } else {
  15. // NOTE: we need to handle unbalanced monitor enter/exit
  16. // in native code by throwing an exception.
  17. // TODO: Throw an IllegalMonitorStateException ?
  18. TEVENT (Exit - Throw IMSX) ;
  19. assert(false, "Non-balanced monitor enter/exit!");
  20. if (false) {
  21. THROW(vmSymbols::java_lang_IllegalMonitorStateException());
  22. }
  23. return;
  24. }
  25. }
  26. //如果當前,線程重入鎖的次數,不為0,那么就重新走ObjectMonitor::exit,直到重入鎖次數為0為止
  27. if (_recursions != 0) {
  28. _recursions--; // this is simple recursive enter
  29. TEVENT (Inflated exit - recursive) ;
  30. return ;
  31. }
  32. ...//此處省略很多代碼
  33. for (;;) {
  34. if (Knob_ExitPolicy == 0) {
  35. OrderAccess::release_store(&_owner, (void*)NULL); //釋放鎖
  36. OrderAccess::storeload(); // See if we need to wake a successor
  37. if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
  38. TEVENT(Inflated exit - simple egress);
  39. return;
  40. }
  41. TEVENT(Inflated exit - complex egress);
  42. //省略部分代碼...
  43. }
  44. //省略部分代碼...
  45. ObjectWaiter * w = NULL;
  46. int QMode = Knob_QMode;
  47. //根據QMode的模式判斷,
  48. //如果QMode == 2則直接從_cxq掛起的線程中喚醒
  49. if (QMode == 2 && _cxq != NULL) {
  50. w = _cxq;
  51. ExitEpilog(Self, w);
  52. return;
  53. }
  54. //省略部分代碼... 省略的代碼為根據QMode的不同,不同的喚醒機制
  55. }
  56. }

根據不同的策略(由QMode指定),從cxq或EntryList中獲取頭節點,通過ObjectMonitor::ExitEpilog方法喚醒該節點封裝的線程,喚醒操作最終由unpark完成

</>復制代碼

  1. void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) {
  2. {
  3. assert (_owner == Self, "invariant") ;
  4. // Exit protocol:
  5. // 1. ST _succ = wakee
  6. // 2. membar #loadstore|#storestore;
  7. // 2. ST _owner = NULL
  8. // 3. unpark(wakee)
  9. _succ = Knob_SuccEnabled ? Wakee->_thread : NULL ;
  10. ParkEvent * Trigger = Wakee->_event ;
  11. // Hygiene -- once we"ve set _owner = NULL we can"t safely dereference Wakee again.
  12. // The thread associated with Wakee may have grabbed the lock and "Wakee" may be
  13. // out-of-scope (non-extant).
  14. Wakee = NULL ;
  15. // Drop the lock
  16. OrderAccess::release_store_ptr (&_owner, NULL) ;
  17. OrderAccess::fence() ; // ST _owner vs LD in unpark()
  18. if (SafepointSynchronize::do_call_back()) {
  19. TEVENT (unpark before SAFEPOINT) ;
  20. }
  21. DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self);
  22. Trigger->unpark() ; //unpark喚醒線程
  23. // Maintain stats and report events to JVMTI
  24. if (ObjectMonitor::_sync_Parks != NULL) {
  25. ObjectMonitor::_sync_Parks->inc() ;
  26. }
  27. }

</>復制代碼

  1. 分析源碼,需要很大的耐心,希望大家能有耐心看下去,有疑問歡迎微信留言

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/72573.html

相關文章

  • SpringMVC之源碼分析--ViewResolver(

    摘要:與一樣,該類繼承抽象類,并且通過外部的屬性文件定義邏輯視圖名稱與真正的視圖對象的關系,屬性文件默認是下的,可以通過或屬性來指定,該屬性指的是文件的基名稱,也就是說以屬性值開頭的屬性文件。 概述 本章再學習另外兩個ViewResolver,分別是XmlViewResolver和ResourceBundleViewResolver,從功能上說,這兩個視圖解析器都是從外部資源文件中查找視圖V...

    alighters 評論0 收藏0
  • 金三銀四,2019大廠Android高級工程師面試題整理

    摘要:原文地址游客前言金三銀四,很多同學心里大概都準備著年后找工作或者跳槽。最近有很多同學都在交流群里求大廠面試題。 最近整理了一波面試題,包括安卓JAVA方面的,目前大廠還是以安卓源碼,算法,以及數據結構為主,有一些中小型公司也會問到混合開發的知識,至于我為什么傾向于混合開發,我的一句話就是走上編程之路,將來你要學不僅僅是這些,豐富自己方能與世接軌,做好全棧的裝備。 原文地址:游客kutd...

    tracymac7 評論0 收藏0

發表評論

0條評論

jhhfft

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<