警告⚠️:本文耗时很长,先做好心理准备................哈哈哈

本篇我们讲通过大量实例代码及hotspot源码分析偏向锁(批量重偏向、批量撤销)、轻量级锁、重量级锁及锁的膨胀过程(也就是锁的升级过程)

我们先来说一下我们为什么需要锁?

因为在并发情况为了保证线程的安全性,是在一个多线程环境下正确性的概念,也就是保证多线程环境下共享的、可修改的状态的正确性(这里的状态指的是程序里的数据),在java程序中我们可以使用synchronized关键字来对程序进行加锁。
当声明synchronized代码块的时候,编译成的字节码将包含monitorenter指令 和 monitorexit指令。这两种指令均会消耗操作数栈上的一个引用类型的元素(也就是 synchronized 关键字括号里的引用),作为所要加锁解锁的锁对象。
(注意:jdk 1.6以前synchronized 关键字只表示重量级锁,1.6之后区分为偏向锁、轻量级锁、重量级锁。)
 
所谓锁的升级、降级,就是 JVM 优化 synchronized 运行的机制,当 JVM 检测到不同的竞争状况时,会自动切换到适合的锁实现,这种切换就是锁的升级、降级:
  • 当没有竞争出现时,默认会使用偏向锁。JVM 会利用 CAS 操作(compare and swap),在对象头上的 Mark Word 部分设置线程 ID,以表示这个对象偏向于当前线程,所以并不涉及真正的互斥锁。这样做的假设是基于在很多应用场景中,大部分对象生命周期中最多会被一个线程锁定,使用偏向锁可以降低无竞争开销。
  • 如果有另外的线程试图锁定某个已经被偏向过的对象,JVM 就需要撤销(revoke)偏向锁,并切换到轻量级锁实现。轻量级锁依赖 CAS 操作 Mark Word 来试图获取锁,如果重试成功,就使用轻量级锁;否则,进一步升级为重量级锁
 
那么我们来看段synchronized代码分析:
java代码:
  1. public class TestDemo {
  2. }
  3. public class DemoExample1 {
  4. static TestDemo testDemo;
  5. public static void main(String[] args) throws Exception {
  6. testDemo= new TestDemo();
  7. synchronized (testDemo){
  8. System.out.println("lock ing");
  9. testDemo.hashCode();
  10. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  11. }
  12. }
  13. }
运行并分析TestDemo.class文件命令:
  1. javap -c DemoExample1.class
 
分析结果:
  1. Compiled from "DemoExample1.java"
  2. public class com.boke.DemoExample1 {
  3. static com.boke.TestDemo testDemo;
  4.  
  5. public com.boke.DemoExample1();
  6. Code:
  7. : aload_0
  8. : invokespecial # // Method java/lang/Object."<init>":()V
  9. : return
  10.  
  11. public static void main(java.lang.String[]) throws java.lang.Exception;
  12. Code:
  13. : new # // class com/boke/TestDemo
  14. : dup
  15. : invokespecial # // Method com/boke/TestDemo."<init>":()V
  16. : putstatic # // Field testDemo:Lcom/boke/TestDemo;
  17. : getstatic # // Field testDemo:Lcom/boke/TestDemo;
  18. : dup
  19. : astore_1
  20. : monitorenter
  21. : getstatic # // Field java/lang/System.out:Ljava/io/PrintStream;
  22. : ldc # // String lock ing
  23. : invokevirtual # // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  24. : getstatic # // Field testDemo:Lcom/boke/TestDemo;
  25. : invokevirtual # // Method java/lang/Object.hashCode:()I
  26. : pop
  27. : getstatic # // Field java/lang/System.out:Ljava/io/PrintStream;
  28. : getstatic # // Field testDemo:Lcom/boke/TestDemo;
  29. : invokestatic # // Method org/openjdk/jol/info/ClassLayout.parseInstance:(Ljava/lang/Object;)Lorg/openjdk/jol/info/ClassLayout;
  30. : invokevirtual # // Method org/openjdk/jol/info/ClassLayout.toPrintable:()Ljava/lang/String;
  31. : invokevirtual # // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  32. : aload_1
  33. : monitorexit
  34. : goto
  35. : astore_2
  36. : aload_1
  37. : monitorexit
  38. : aload_2
  39. : athrow
  40. : return
  41. Exception table:
  42. from to target type
  43. any
  44. any
  45. }
通过字节码可以看出包含一个monitorenter指令以及多个monitorexit指令。这是因为jvm需要确保所获得的锁在正常执行路径,以及异常执行路径上都能够被解锁。
 
我们可以抽象的理解为每个锁对象拥有一个锁计数器和一个指向持有该锁的线程的指针
  • 当执行 monitorenter 时,如果目标锁对象的计数器为 0,那么说明它没有被其他线程所持有。在这个情况下,Java 虚拟机会将该锁对象的持有线程设置为当前线程,并且将其计数器加 1。
  • 在目标锁对象的计数器不为 0 的情况下,如果锁对象的持有线程是当前线程,那么 Java 虚拟机可以将其计数器加 1,否则需要等待,直至持有线程释放该锁。当执行 monitorexit 时,Java 虚拟机则需将锁对象的计数器减 1。当计数器减为 0 时,那便代表该锁已经被释放掉了。
  • 之所以采用这种计数器的方式,是为了允许同一个线程重复获取同一把锁。举个例子,如果一个 Java 类中拥有多个 synchronized 方法,那么这些方法之间的相互调用,不管是直接的还是间接的,都会涉及对同一把锁的重复加锁操作。因此,我们需要设计这么一个可重入的特性,来避免编程里的隐式约束。
  
我们来看一个案例:在不加锁的情况多下通过取两次数值然后进行对比,来模拟两次共享状态的操作:
java代码:
  1. public class DemoExample3 {
  2. public int sharedState;
  3.  
  4. public void nonSafeAction() {
  5. while (sharedState < ) {
  6. int former = sharedState++;
  7. int latter = sharedState;
  8. if (former != latter - ) {
  9. System.out.println("Observed data race, former is " +
  10. former + ", " + "latter is " + latter);
  11. }
  12. }
  13. }
  14.  
  15. public static void main(String[] args) throws InterruptedException {
  16. final DemoExample3 demoExample3 = new DemoExample3();
  17. Thread thread1 = new Thread() {
  18. @Override
  19. public void run() {
  20. demoExample3.nonSafeAction();
  21. }
  22. };
  23.  
  24. Thread thread2 = new Thread() {
  25. @Override
  26. public void run() {
  27. demoExample3.nonSafeAction();
  28. }
  29. };
  30.  
  31. thread1.start();
  32. thread2.start();
  33. thread1.join();
  34. thread2.join();
  35. }
  36. }
在没有加 synchronized 关键字的时候打印出来的结果(截取部分):
  1. Observed data race, former is , latter is
  2. Observed data race, former is , latter is
  3. Observed data race, former is , latter is
  4. Observed data race, former is , latter is
  5. Observed data race, former is , latter is
  6. Observed data race, former is , latter is
  7. Observed data race, former is , latter is
  8. Observed data race, former is , latter is
  9. Observed data race, former is , latter is
  10. Observed data race, former is , latter is
  11. Observed data race, former is , latter is
  12. Observed data race, former is , latter is
  13. Observed data race, former is , latter is
就会发现,打印出好多与if (former != latter - 1) 条件相符的值,这是错误的,正确的结果应该是一条也没有;
 
我们在来看一下加上synchronized关键字的代码:
java代码:
  1. public class DemoExample3 {
  2. public int sharedState;
  3.  
  4. public void nonSafeAction() {
  5. while (sharedState < ) {
  6. synchronized (this) {
  7. int former = sharedState++;
  8. int latter = sharedState;
  9. if (former != latter - ) {
  10. System.out.println("Observed data race, former is " +
  11. former + ", " + "latter is " + latter);
  12. }
  13. }
  14. }
  15. }
  16.  
  17. public static void main(String[] args) throws InterruptedException {
  18. final DemoExample3 demoExample3 = new DemoExample3();
  19. Thread thread1 = new Thread() {
  20. @Override
  21. public void run() {
  22. demoExample3.nonSafeAction();
  23. }
  24. };
  25.  
  26. Thread thread2 = new Thread() {
  27. @Override
  28. public void run() {
  29. demoExample3.nonSafeAction();
  30. }
  31. };
  32. thread1.start();
  33. thread2.start();
  34. thread1.join();
  35. thread2.join();
  36. }
  37. }

这次看下加上synchronized关键字的打印出来的结果:

  1. Process finished with exit code
说明将两次赋值过程用synchronized保护起来,使用this作为互斥单元,就可以避免别的线程并发的去修改sharedState;这也就是我刚开说的并发情况下为了保证线程的安全性,我们可以通过加锁来保证。
 

说完我们为什么需要锁,接下来我们介绍偏向锁、轻量级锁、重量级锁及锁的膨胀过程

首先我们先从jvm源码中来分析锁的膨胀过程(锁升级的过程):
在jvm中synchronized的是行为是jvm runntime的一部分,所以我们需要先找到 Runtime 相关的功能实现。通过在代码中查询类似“monitor_enter”或“Monitor Enter”,很直观的就可以定位到:
sharedRuntime.cpp(http://hg.openjdk.java.net/jdk/jdk/file/6659a8f57d78/src/hotspot/share/runtime/sharedRuntime.cpp),它是解释器和编译器运行时的基类:
  1. // Handles the uncommon case in locking, i.e., contention or an inflated lock.
  2. JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* _obj, BasicLock* lock, JavaThread* thread))
  3. // Disable ObjectSynchronizer::quick_enter() in default config
  4. // on AARCH64 and ARM until JDK-8153107 is resolved.
  5. if (ARM_ONLY((SyncFlags & ) != &&)
  6. AARCH64_ONLY((SyncFlags & ) != &&)
  7. !SafepointSynchronize::is_synchronizing()) {
  8. // Only try quick_enter() if we're not trying to reach a safepoint
  9. // so that the calling thread reaches the safepoint more quickly.
  10. if (ObjectSynchronizer::quick_enter(_obj, thread, lock)) return;
  11. }
  12. // NO_ASYNC required because an async exception on the state transition destructor
  13. // would leave you with the lock held and it would never be released.
  14. // The normal monitorenter NullPointerException is thrown without acquiring a lock
  15. // and the model is that an exception implies the method failed.
  16. JRT_BLOCK_NO_ASYNC
  17. oop obj(_obj);
  18. if (PrintBiasedLockingStatistics) {
  19. Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
  20. }
  21. Handle h_obj(THREAD, obj);
  22. //在 JVM 启动时,我们可以指定是否开启偏向锁
  23. if (UseBiasedLocking) {
  24. // Retry fast entry if bias is revoked to avoid unnecessary inflation
  25. <strong> //fast_enter 是我们熟悉的完整锁获取路径</strong>
  26. ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
  27. } else {
  28. //slow_enter 则是绕过偏向锁,直接进入轻量级锁获取逻辑
  29. ObjectSynchronizer::slow_enter(h_obj, lock, CHECK);
  30. }
  31. assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
  32. JRT_BLOCK_END
  33. JRT_END
synchronizer.cpp(https://hg.openjdk.java.net/jdk/jdk/file/896e80158d35/src/hotspot/share/runtime/synchronizer.cpp),JVM 同步相关的各种基础(不仅仅是 synchronized 的逻辑,包括从本地代码,也就是 JNI,触发的 Monitor 动作,全都可以在里面找到例如(jni_enter/jni_exit)):
  1. // -----------------------------------------------------------------------------
  2. // Fast Monitor Enter/Exit
  3. // This the fast monitor enter. The interpreter and compiler use
  4. // some assembly copies of this code. Make sure update those code
  5. // if the following function is changed. The implementation is
  6. // extremely sensitive to race condition. Be careful.
  7. void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock,
  8. bool attempt_rebias, TRAPS) {
  9. if (UseBiasedLocking) {
  10. if (!SafepointSynchronize::is_at_safepoint()) {
  11. //biasedLocking定义了偏向锁相关操作,revoke_and_rebias revokeatsafepoint 则定义了当检测到安全点时的处理
  12. BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD);
  13. if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) {
  14. return;
  15. }
  16. } else {
  17. assert(!attempt_rebias, "can not rebias toward VM thread");
  18. BiasedLocking::revoke_at_safepoint(obj);
  19. }
  20. assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
  21. }
  22. //如果获取偏向锁失败,则进入 slow_enter,锁升级
  23. slow_enter(obj, lock, THREAD);
  24. }
  25.  
  26. // -----------------------------------------------------------------------------
  27. // Interpreter/Compiler Slow Case
  28. // This routine is used to handle interpreter/compiler slow case
  29. // We don't need to use fast path here, because it must have been
  30. // failed in the interpreter/compiler code.
  31. void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
  32. markOop mark = obj->mark();
  33. assert(!mark->has_bias_pattern(), "should not see bias pattern here");
  34. if (mark->is_neutral()) {
  35. // Anticipate successful CAS -- the ST of the displaced mark must
  36. // be visible <= the ST performed by the CAS.
  37. // 将目前的 Mark Word 复制到 Displaced Header 上
  38. lock->set_displaced_header(mark);
  39. // 利用 CAS 设置对象的 Mark Wo
  40. if (mark == obj()->cas_set_mark((markOop) lock, mark)) {
  41. return;
  42. }
  43. // Fall through to inflate() …
  44. // 检查存在竞争
  45. } else if (mark->has_locker() &&
  46. THREAD->is_lock_owned((address)mark->locker())) {
  47. assert(lock != mark->locker(), "must not re-lock the same lock");
  48. assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock”);
  49. // 清除
  50. lock->set_displaced_header(NULL);
  51. return;
  52. }
  53. // The object header will never be displaced to this lock,
  54. // so it does not matter what the value is, except that it
  55. // must be non-zero to avoid looking like a re-entrant lock,
  56. // and must not look locked either.
  57. // 重置 Displaced Header
  58. lock->set_displaced_header(markOopDesc::unused_mark());
  59. //锁膨胀
  60. ObjectSynchronizer::inflate(THREAD,
  61. obj(),
  62. inflate_cause_monitor_enter)->enter(THREAD);
  63. }
  64. // This routine is used to handle interpreter/compiler slow case
  65. // We don't need to use fast path here, because it must have
  66. // failed in the interpreter/compiler code. Simply use the heavy
  67. // weight monitor should be ok, unless someone find otherwise.
  68. void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
  69. fast_exit(object, lock, THREAD);
  70. }
  71.  
  72. //锁膨胀
  73. ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
  74. // Inflate mutates the heap ...
  75. // Relaxing assertion for bug 6320749.
  76. assert (Universe::verify_in_progress() ||
  77. !SafepointSynchronize::is_at_safepoint(), "invariant") ;
  78.  
  79. for (;;) {//自旋
  80. const markOop mark = object->mark() ;
  81. assert (!mark->has_bias_pattern(), "invariant") ;
  82.  
  83. // The mark can be in one of the following states:
  84. // * Inflated - just return
  85. // * Stack-locked - coerce it to inflated
  86. // * INFLATING - busy wait for conversion to complete
  87. // * Neutral - aggressively inflate the object.
  88. // * BIASED - Illegal. We should never see this
  89.  
  90. // CASE: inflated已膨胀,即重量级锁
  91. if (mark->has_monitor()) {//判断当前是否为重量级锁
  92. ObjectMonitor * inf = mark->monitor() ;//获取指向ObjectMonitor的指针
  93. assert (inf->header()->is_neutral(), "invariant");
  94. assert (inf->object() == object, "invariant") ;
  95. assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
  96. return inf ;
  97. }
  98.  
  99. // CASE: inflation in progress - inflating over a stack-lock.膨胀等待(其他线程正在从轻量级锁转为膨胀锁)
  100. // Some other thread is converting from stack-locked to inflated.
  101. // Only that thread can complete inflation -- other threads must wait.
  102. // The INFLATING value is transient.
  103. // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
  104. // We could always eliminate polling by parking the thread on some auxiliary list.
  105. if (mark == markOopDesc::INFLATING()) {
  106. TEVENT (Inflate: spin while INFLATING) ;
  107. ReadStableMark(object) ;
  108. continue ;
  109. }
  110.  
  111. // CASE: stack-locked栈锁(轻量级锁)
  112. // Could be stack-locked either by this thread or by some other thread.
  113. //
  114. // Note that we allocate the objectmonitor speculatively, _before_ attempting
  115. // to install INFLATING into the mark word. We originally installed INFLATING,
  116. // allocated the objectmonitor, and then finally STed the address of the
  117. // objectmonitor into the mark. This was correct, but artificially lengthened
  118. // the interval in which INFLATED appeared in the mark, thus increasing
  119. // the odds of inflation contention.
  120. //
  121. // We now use per-thread private objectmonitor free lists.
  122. // These list are reprovisioned from the global free list outside the
  123. // critical INFLATING...ST interval. A thread can transfer
  124. // multiple objectmonitors en-mass from the global free list to its local free list.
  125. // This reduces coherency traffic and lock contention on the global free list.
  126. // Using such local free lists, it doesn't matter if the omAlloc() call appears
  127. // before or after the CAS(INFLATING) operation.
  128. // See the comments in omAlloc().
  129.  
  130. if (mark->has_locker()) {
  131. ObjectMonitor * m = omAlloc (Self) ;//获取一个可用的ObjectMonitor
  132. // Optimistically prepare the objectmonitor - anticipate successful CAS
  133. // We do this before the CAS in order to minimize the length of time
  134. // in which INFLATING appears in the mark.
  135. m->Recycle();
  136. m->_Responsible = NULL ;
  137. m->OwnerIsThread = ;
  138. m->_recursions = ;
  139. m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // Consider: maintain by type/class
  140.  
  141. markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ;
  142. if (cmp != mark) {//CAS失败//CAS失败,说明冲突了,自旋等待//CAS失败,说明冲突了,自旋等待//CAS失败,说明冲突了,自旋等待
  143. omRelease (Self, m, true) ;//释放监视器锁
  144. continue ; // Interference -- just retry
  145. }
  146.  
  147. // We've successfully installed INFLATING (0) into the mark-word.
  148. // This is the only case where 0 will appear in a mark-work.
  149. // Only the singular thread that successfully swings the mark-word
  150. // to 0 can perform (or more precisely, complete) inflation.
  151. //
  152. // Why do we CAS a 0 into the mark-word instead of just CASing the
  153. // mark-word from the stack-locked value directly to the new inflated state?
  154. // Consider what happens when a thread unlocks a stack-locked object.
  155. // It attempts to use CAS to swing the displaced header value from the
  156. // on-stack basiclock back into the object header. Recall also that the
  157. // header value (hashcode, etc) can reside in (a) the object header, or
  158. // (b) a displaced header associated with the stack-lock, or (c) a displaced
  159. // header in an objectMonitor. The inflate() routine must copy the header
  160. // value from the basiclock on the owner's stack to the objectMonitor, all
  161. // the while preserving the hashCode stability invariants. If the owner
  162. // decides to release the lock while the value is 0, the unlock will fail
  163. // and control will eventually pass from slow_exit() to inflate. The owner
  164. // will then spin, waiting for the 0 value to disappear. Put another way,
  165. // the 0 causes the owner to stall if the owner happens to try to
  166. // drop the lock (restoring the header from the basiclock to the object)
  167. // while inflation is in-progress. This protocol avoids races that might
  168. // would otherwise permit hashCode values to change or "flicker" for an object.
  169. // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
  170. // 0 serves as a "BUSY" inflate-in-progress indicator
  171. // fetch the displaced mark from the owner's stack.
  172. // The owner can't die or unwind past the lock while our INFLATING
  173. // object is in the mark. Furthermore the owner can't complete
  174. // an unlock on the object, either.
  175. markOop dmw = mark->displaced_mark_helper() ;
  176. assert (dmw->is_neutral(), "invariant") ;
  177. //CAS成功,设置ObjectMonitor的_header、_owner和_object等
  178. // Setup monitor fields to proper values -- prepare the monitor
  179. m->set_header(dmw) ;
  180.  
  181. // Optimization: if the mark->locker stack address is associated
  182. // with this thread we could simply set m->_owner = Self and
  183. // m->OwnerIsThread = 1. Note that a thread can inflate an object
  184. // that it has stack-locked -- as might happen in wait() -- directly
  185. // with CAS. That is, we can avoid the xchg-NULL .... ST idiom.
  186. m->set_owner(mark->locker());
  187. m->set_object(object);
  188. // TODO-FIXME: assert BasicLock->dhw != 0.
  189.  
  190. // Must preserve store ordering. The monitor state must
  191. // be stable at the time of publishing the monitor address.
  192. guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
  193. object->release_set_mark(markOopDesc::encode(m));
  194.  
  195. // Hopefully the performance counters are allocated on distinct cache lines
  196. // to avoid false sharing on MP systems ...
  197. if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
  198. TEVENT(Inflate: overwrite stacklock) ;
  199. if (TraceMonitorInflation) {
  200. if (object->is_instance()) {
  201. ResourceMark rm;
  202. tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  203. (void *) object, (intptr_t) object->mark(),
  204. object->klass()->external_name());
  205. }
  206. }
  207. return m ;
  208. }
  209.  
  210. // CASE: neutral 无锁
  211. // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
  212. // If we know we're inflating for entry it's better to inflate by swinging a
  213. // pre-locked objectMonitor pointer into the object header. A successful
  214. // CAS inflates the object *and* confers ownership to the inflating thread.
  215. // In the current implementation we use a 2-step mechanism where we CAS()
  216. // to inflate and then CAS() again to try to swing _owner from NULL to Self.
  217. // An inflateTry() method that we could call from fast_enter() and slow_enter()
  218. // would be useful.
  219.  
  220. assert (mark->is_neutral(), "invariant");
  221. ObjectMonitor * m = omAlloc (Self) ;
  222. // prepare m for installation - set monitor to initial state
  223. m->Recycle();
  224. m->set_header(mark);
  225. m->set_owner(NULL);
  226. m->set_object(object);
  227. m->OwnerIsThread = ;
  228. m->_recursions = ;
  229. m->_Responsible = NULL ;
  230. m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // consider: keep metastats by type/class
  231.  
  232. if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) {
  233. m->set_object (NULL) ;
  234. m->set_owner (NULL) ;
  235. m->OwnerIsThread = ;
  236. m->Recycle() ;
  237. omRelease (Self, m, true) ;
  238. m = NULL ;
  239. continue ;
  240. // interference - the markword changed - just retry.
  241. // The state-transitions are one-way, so there's no chance of
  242. // live-lock -- "Inflated" is an absorbing state.
  243. }
  244.  
  245. // Hopefully the performance counters are allocated on distinct
  246. // cache lines to avoid false sharing on MP systems ...
  247. if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
  248. TEVENT(Inflate: overwrite neutral) ;
  249. if (TraceMonitorInflation) {
  250. if (object->is_instance()) {
  251. ResourceMark rm;
  252. tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  253. (void *) object, (intptr_t) object->mark(),
  254. object->klass()->external_name());
  255. }
  256. }
  257. return m ;
  258. }
  259. }
膨胀过程的实现比较复杂,大概实现过程如下:

1、整个膨胀过程在自旋下完成;

2、mark->has_monitor()方法判断当前是否为重量级锁,即Mark Word的锁标识位为 10,如果当前状态为重量级锁,执行步骤(3),否则执行步骤(4);

3、mark->monitor()方法获取指向ObjectMonitor的指针,并返回,说明膨胀过程已经完成;

4、如果当前锁处于膨胀中,说明该锁正在被其它线程执行膨胀操作,则当前线程就进行自旋等待锁膨胀完成,这里需要注意一点,虽然是自旋操作,但不会一直占用cpu资源,每隔一段时间会通过os::NakedYield方法放弃cpu资源,或通过park方法挂起;如果其他线程完成锁的膨胀操作,则退出自旋并返回;

5、如果当前是轻量级锁状态,即锁标识位为 00,膨胀过程如下:

  • 通过omAlloc方法,获取一个可用的ObjectMonitor monitor,并重置monitor数据;
  • 通过CAS尝试将Mark Word设置为markOopDesc:INFLATING,标识当前锁正在膨胀中,如果CAS失败,说明同一时刻其它线程已经将Mark Word设置为markOopDesc:INFLATING,当前线程进行自旋等待膨胀完成;
  • 如果CAS成功,设置monitor的各个字段:_header、_owner和_object等,并返回;

6、如果是无锁,重置监视器值;

 
以上就是从jvm源码来分析锁的膨胀过程了。
 

接下来我们案例入手开始分析偏向锁(批量重偏向、批量撤销)、轻量级锁、重量级锁及膨胀过程:

偏向锁:

  • 偏向锁是指一段同步代码一直被一个线程所访问,那么该线程会自动获取锁,降低获取锁的代价。
  • 在大多数情况下,锁总是由同一线程多次获得,不存在多线程竞争,所以出现了偏向锁。其目标就是在只有一个线程执行同步代码块时能够提高性能。
  • 当一个线程访问同步代码块并获取锁时,会在Mark Word里存储锁偏向的线程ID。在线程进入和退出同步块时不再通过CAS操作来加锁和解锁,而是检测Mark Word里是否存储着指向当前线程的偏向锁。引入偏向锁是为了在无多线程竞争的情况下尽量减少不必要的轻量级锁执行路径,因为轻量级锁的获取及释放依赖多次CAS原子指令,而偏向锁只需要在置换ThreadID的时候依赖一次CAS原子指令即可。
  • 偏向锁只有遇到其他线程尝试竞争偏向锁时,持有偏向锁的线程才会释放锁,线程不会主动释放偏向锁。偏向锁的撤销,需要等待全局安全点(在这个时间点上没有字节码正在执行),它会首先暂停拥有偏向锁的线程,判断锁对象是否处于被锁定状态。撤销偏向锁后恢复到无锁(标志位为“01”)或轻量级锁(标志位为“00”)的状态。
  • 偏向锁在JDK 6及以后的JVM里是默认启用的。可以通过JVM参数关闭偏向锁:-XX:-UseBiasedLocking=false,关闭之后程序默认会进入轻量级锁状态。
 
在上篇【java并发笔记三之synchronized 偏向锁 轻量级锁 重量级锁证明】说过偏向锁在没有禁止延迟的时候还没加锁之前就已经是偏向锁了,但是加锁完之后,退出同步代码块 还是偏向锁;计算过hashcode之后就不能被偏向。
一、我们来看段代码证明下,在没有计算hashcode的情况下:
  1. //创建一个啥都没有的类:
  2. public class TestDemo {}
  3.  
  4. public class DemoExample {
  5. static TestDemo testDemo;
  6. public static void main(String[] args) throws Exception {
  7. //此处睡眠50000ms,取消jvm默认偏向锁延迟4000ms
  8. Thread.sleep();
  9. testDemo= new TestDemo();
  10.  
  11. //hash计算?
  12. //testDemo.hashCode();
  13.  
  14. System.out.println("befor lock");
  15. //无锁:偏向锁?
  16. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  17.  
  18. synchronized (testDemo){
  19. System.out.println("lock ing");
  20. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  21. }
  22.  
  23. System.out.println("after lock");
  24. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  25. }
  26. }
运行结果:
  1. befor lock
  2. OFFSET SIZE TYPE DESCRIPTION VALUE
  3. (object header) ( ) ()
  4. (object header) ( ) ()
  5. (object header) c1 f8 ( ) (-)
  6. (loss due to the next object alignment)
  7. Instance size: bytes
  8. Space losses: bytes internal + bytes external = bytes total
  9.  
  10. lock ing
  11. com.boke.TestDemo object internals:
  12. OFFSET SIZE TYPE DESCRIPTION VALUE
  13. (object header) ac ( ) (-)
  14. (object header) 8d 7f ( ) ()
  15. (object header) c1 f8 ( ) (-)
  16. (loss due to the next object alignment)
  17. Instance size: bytes
  18. Space losses: bytes internal + bytes external = bytes total
  19.  
  20. after lock
  21. com.boke.TestDemo object internals:
  22. OFFSET SIZE TYPE DESCRIPTION VALUE
  23. (object header) ac ( ) (-)
  24. (object header) 8d 7f ( ) ()
  25. (object header) c1 f8 ( ) (-)
  26. (loss due to the next object alignment)
  27. Instance size: bytes
  28. Space losses: bytes internal + bytes external = bytes total
分析结果:
befor lock:绿颜色表示:虽然是偏向锁,但是黄颜色表示没有任何线程持有锁(一个对象被初始化的时候是可偏向的)
lock  ing: 绿颜色表示偏向锁,黄颜色的表示当前线程拿到锁
after lock:绿颜色表示偏向锁,黄颜色的表示当前线程拿到锁,还是偏向的状态;(偏向锁退出锁后依然是偏向状态)
 
jvm在初始化一个对象的时候,如果没有启用偏向锁延迟,就会去判断这个对象是否可以被偏向,如果可以就是偏向锁;退出同步代码块 还是偏向锁。
 
二、在对象进行hashcode计算之后就会输出下面的结果(也就是代码的这块testDemo.hashCode()去掉注释,进行hashcode运算):
  1. befor lock
  2. com.boke.TestDemo object internals:
  3. OFFSET SIZE TYPE DESCRIPTION VALUE
  4. (object header) ( ) ()
  5. (object header) ( ) ()
  6. (object header) c1 f8 ( ) (-)
  7. (loss due to the next object alignment)
  8. Instance size: bytes
  9. Space losses: bytes internal + bytes external = bytes total
  10.  
  11. lock ing
  12. com.boke.TestDemo object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. (object header) f8 4b 0c ( ) ()
  15. (object header) ( ) ()
  16. (object header) c1 f8 ( ) (-)
  17. (loss due to the next object alignment)
  18. Instance size: bytes
  19. Space losses: bytes internal + bytes external = bytes total
  20.  
  21. after lock
  22. com.boke.TestDemo object internals:
  23. OFFSET SIZE TYPE DESCRIPTION VALUE
  24. (object header) ac ( ) (-)
  25. (object header) 8d 7f ( ) ()
  26. (object header) c1 f8 ( ) (-)
  27. (loss due to the next object alignment)
  28. Instance size: bytes
  29. Space losses: bytes internal + bytes external = bytes total
结果显示并不是偏向锁了,说明对象在计算过hashcode之后就不能被偏向;
  1. 具体来说,在线程进行加锁时,如果该锁对象支持偏向锁,那么 Java 虚拟机会通过 CAS操作,将当前线程的地址记录在锁对象的标记字段之中,并且将标记字段的最后三位设置为:1 01;
  2. 在接下来的运行过程中,每当有线程请求这把锁,Java 虚拟机只需判断锁对象标记字段中:最后三位是否为: 1 01,是否包含当前线程的地址,以及 epoch 值是否和锁对象的类的epoch 值相同。如果都满足,那么当前线程持有该偏向锁,可以直接返回;

这里的 epoch 值是一个什么概念呢?

  • 我们先从偏向锁的撤销讲起。当请求加锁的线程和锁对象标记字段保持的线程地址不匹配时(而且 epoch 值相等,如若不等,那么当前线程可以将该锁重偏向至自己),Java 虚拟机需要撤销该偏向锁。这个撤销过程非常麻烦,它要求持有偏向锁的线程到达安全点,再将偏向锁替换成轻量级锁;
  • 如果某一类锁对象的总撤销数超过了一个阈值(对应 jvm参数 -XX:BiasedLockingBulkRebiasThreshold,默认为 20),那么 Java 虚拟机会宣布这个类的偏向锁失效;(这里说的就是批量重偏向)
       JVM源码:
  1. product(intx, BiasedLockingBulkRebiasThreshold, , \
  2. "Threshold of number of revocations per type to try to " \
  3. "rebias all objects in the heap of that type") \
  4. range(, max_intx) \
  5. constraint(BiasedLockingBulkRebiasThresholdFunc,AfterErgo) \
  • 具体的做法便是在每个类中维护一个 epoch 值,你可以理解为第几代偏向锁。当设置偏向锁时,Java 虚拟机需要将该 epoch 值复制到锁对象的标记字段中;
  • 在宣布某个类的偏向锁失效时,Java 虚拟机实则将该类的 epoch 值加 1,表示之前那一代的偏向锁已经失效。而新设置的偏向锁则需要复制新的 epoch 值;
  • 为了保证当前持有偏向锁并且已加锁的线程不至于因此丢锁,Java 虚拟机需要遍历所有线程的 Java 栈,找出该类已加锁的实例,并且将它们标记字段中的 epoch 值加 1。该操作需要所有线程处于安全点状态;
  • 如果总撤销数超过另一个阈值(对应 jvm 参数 -XX:BiasedLockingBulkRevokeThreshold,默认值为 40),那么 Java 虚拟机会认为这个类已经不再适合偏向锁。此时,Java 虚拟机会撤销该类实例的偏向锁,并且在之后的加锁过程中直接为该类实例设置轻量级锁(这里说的就是偏向批量撤销)
      
JVM源码:
  1. product(intx, BiasedLockingBulkRevokeThreshold, , \
  2. "Threshold of number of revocations per type to permanently " \
  3. "revoke biases of all objects in the heap of that type") \
  4. range(, max_intx) \
  5. constraint(BiasedLockingBulkRevokeThresholdFunc,AfterErgo)
接下来我们分析两个批量重偏向相关案例(禁止偏向锁延迟的情况下:-XX:+UseBiasedLocking -XX:BiasedLockingStartupDelay=0):
 
案例一:
java代码:
  1. public class TestDemo {
  2. }
  3. public class DemoExample4 {
  4. public static void main(String[] args) throws InterruptedException {
  5. test1();
  6. }
  7.  
  8. public class DemoExample5 {
  9. public static void main(String[] args) throws InterruptedException {
  10. test1();
  11. }
  12.  
  13. /**
  14. * 仅证明批量重偏向
  15. * @throws InterruptedException
  16. */
  17. public static void test1() throws InterruptedException {
  18. List<TestDemo> list = new ArrayList<>();
  19. for (int i = ; i < ; i++) {
  20. list.add(new TestDemo());
  21. }
  22. Thread t1 = new Thread(()->{
  23. System.out.println("加锁前 get(0) 应该是无锁可偏向 "+ ClassLayout.parseInstance(list.get()).toPrintable());
  24. for (TestDemo a:list ) {
  25. synchronized (a){
  26. System.out.print("加锁 >");
  27. }
  28. }
  29. System.out.println();
  30. System.out.println("加锁后 get(0) 应该是偏向锁"+ClassLayout.parseInstance(list.get()).toPrintable());
  31. try {
  32. TimeUnit.SECONDS.sleep();//这里不让线程死,防止线程ID复用
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. });
  37. t1.start();
  38. TimeUnit.SECONDS.sleep();
  39. Thread t2 = new Thread(()->{
  40. for (int i = ; i < ; i++) {
  41. TestDemo a = list.get(i);
  42. synchronized (a){
  43. System.out.print("加锁 >");
  44. }
  45. if (i==){
  46. System.out.println();
  47. System.out.println("加锁后 get(18) 应该是无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  48. }
  49. if (i==){ //开始重偏向
  50. System.out.println();
  51. System.out.println("加锁后 get(19) 应该是偏向锁 "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  52. System.out.println("加锁后 get(0) 应该是无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get()).toPrintable());
  53. System.out.println("加锁后 get(99) 应该是偏向锁 偏向t1 "+ClassLayout.parseInstance(list.get()).toPrintable());
  54. }
  55. if (i==){
  56. System.out.println();
  57. System.out.println("加锁后 get(20) 应该是偏向锁 "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  58. }
  59. }
  60. });
  61. t2.start();
  62. }
  63. }
运行并分析结果:
  1. com.boke.TestDemo object internals:
  2. OFFSET SIZE TYPE DESCRIPTION VALUE
  3. (object header) ( ) ()
  4. (object header) ( ) ()
  5. (object header) c1 f8 ( ) (-)
  6. (loss due to the next object alignment)
  7. Instance size: bytes
  8. Space losses: bytes internal + bytes external = bytes total
  9.  
  10. 加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
  11.  
  12. 加锁后 get() 应该是偏向锁com.boke.TestDemo object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. (object header) 8a ( ) ()
  15. (object header) c4 7f ( ) ()
  16. (object header) c1 f8 ( ) (-)
  17. (loss due to the next object alignment)
  18. Instance size: bytes
  19. Space losses: bytes internal + bytes external = bytes total
  20.  
  21. 加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
  22. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  23. OFFSET SIZE TYPE DESCRIPTION VALUE
  24. (object header) ( ) ()
  25. (object header) ( ) ()
  26. (object header) c1 f8 ( ) (-)
  27. (loss due to the next object alignment)
  28. Instance size: bytes
  29. Space losses: bytes internal + bytes external = bytes total
  30.  
  31. 加锁 >
  32. 加锁后 get() 应该是偏向锁 com.boke.TestDemo object internals:
  33. OFFSET SIZE TYPE DESCRIPTION VALUE
  34. (object header) 0b ( ) ()
  35. (object header) c4 7f ( ) ()
  36. (object header) c1 f8 ( ) (-)
  37. (loss due to the next object alignment)
  38. Instance size: bytes
  39. Space losses: bytes internal + bytes external = bytes total
  40.  
  41. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  42. OFFSET SIZE TYPE DESCRIPTION VALUE
  43. (object header) ( ) ()
  44. (object header) ( ) ()
  45. (object header) c1 f8 ( ) (-)
  46. (loss due to the next object alignment)
  47. Instance size: bytes
  48. Space losses: bytes internal + bytes external = bytes total
  49.  
  50. 加锁后 get() 应该是偏向锁 偏向t1 com.boke.TestDemo object internals:
  51. OFFSET SIZE TYPE DESCRIPTION VALUE
  52. (object header) 8a ( ) ()
  53. (object header) c4 7f ( ) ()
  54. (object header) c1 f8 ( ) (-)
  55. (loss due to the next object alignment)
  56. Instance size: bytes
  57. Space losses: bytes internal + bytes external = bytes total
  58.  
  59. 加锁 >
  60. 加锁后 get() 应该是偏向锁 com.boke.TestDemo object internals:
  61. OFFSET SIZE TYPE DESCRIPTION VALUE
  62. (object header) 0b ( ) ()
  63. (object header) c4 7f ( ) ()
  64. (object header) c1 f8 ( ) (-)
  65. (loss due to the next object alignment)
  66. Instance size: bytes
  67. Space losses: bytes internal + bytes external = bytes total
  68.  
  69. 加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
案例二:
java代码:
  1. public class TestDemo {
  2. }
  3. public class DemoExample7 {
  4. public static void main(String[] args) throws Exception {
  5.  
  6. List<TestDemo> list = new ArrayList<>();
  7. //初始化数据
  8. for (int i = ; i < ; i++) {
  9. list.add(new TestDemo());
  10. }
  11.  
  12. Thread t1 = new Thread() {
  13. String name = "";
  14. public void run() {
  15. System.out.printf(name);
  16. for (TestDemo a : list) {
  17. synchronized (a) {
  18. if (a == list.get()) {
  19. System.out.println("t1 预期是偏向锁" + + ClassLayout.parseInstance(a).toPrintable());
  20. }
  21. }
  22. }
  23. try {
  24. Thread.sleep();
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. };
  30. t1.start();
  31. Thread.sleep();
  32. System.out.println("main 预期是偏向锁" + + ClassLayout.parseInstance(list.get()).toPrintable());
  33.  
  34. Thread t2 = new Thread() {
  35. String name = "";
  36.  
  37. public void run() {
  38. System.out.printf(name);
  39. for (int i = ; i < ; i++) {
  40. TestDemo a = list.get(i);
  41. // hack 为了在批量重偏向发生后再次加锁,前面使用了轻量级锁的对象
  42. if (i == ) {
  43. a = list.get();
  44. }
  45.  
  46. synchronized (a) {
  47. if (i == ) {
  48. //已经经过偏向锁撤销,并使用轻量级锁的对象,释放后 状态依为001 无锁状态
  49. System.out.println("t2 i=10 get(1)预期是无锁" + ClassLayout.parseInstance(list.get()).toPrintable());
  50. //因为和t1交替使用对象a 没有发生竞争,但偏向锁已偏向,另外不满足重偏向条件,所以使用轻量级锁
  51. System.out.println("t2 i=10 get(i) 预期轻量级锁 " + i + ClassLayout.parseInstance(a).toPrintable());
  52. }
  53. if (i == ) {
  54. //已经经过偏向锁撤销,并使用轻量级锁的对象,在批量重偏向发生后。不会影响现有的状态 状态依然为001
  55. System.out.println("t2 i=19 get(10)预期是无锁" + + ClassLayout.parseInstance(list.get()).toPrintable());
  56. //满足重偏向条件后,已偏向的对象可以重新使用偏向锁 将线程id指向当前线程,101
  57. System.out.println("t2 i=19 get(i) 满足重偏向条件20 预期偏向锁 " + i + ClassLayout.parseInstance(a).toPrintable());
  58. //满足重偏向条件后,已偏向还为需要加锁的对象依然偏向线程1 因为偏向锁的撤销是发生在下次加锁的时候。这里没有执行到同步此对象,所以依然偏向t1
  59. System.out.println("t2 i=19 get(i) 满足重偏向条件20 但后面的对象没有被加锁,所以依旧偏向t1 " + i + ClassLayout.parseInstance(list.get()).toPrintable());
  60. }
  61. if (i == ) {
  62. //满足重偏向条件后,再次加锁之前使用了轻量级锁的对象,依然轻量级锁,证明重偏向这个状态只针对偏向锁。已经发生锁升级的,不会退回到偏向锁
  63. System.out.println("t2 i=20 满足偏向条件之后,之前被设置为无锁状态的对象,不可偏向,这里使用的是轻量级锁 get(9)预期是轻量级锁 " + ClassLayout.parseInstance(a).toPrintable());
  64. }
  65. }
  66. }
  67. try {
  68. Thread.sleep();
  69. } catch (InterruptedException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. };
  74. t2.start();
  75. Thread.sleep();
  76. }
  77. }
运行并分析结果:
  1. t1 预期是偏向锁10 com.boke.TestDemo object internals:
  2. OFFSET SIZE TYPE DESCRIPTION VALUE
  3. (object header) af ( ) (-)
  4. (object header) f6 7f ( ) ()
  5. (object header) d6 f8 ( ) (-)
  6. (loss due to the next object alignment)
  7. Instance size: bytes
  8. Space losses: bytes internal + bytes external = bytes total
  9.  
  10. main 预期是偏向锁 com.boke.TestDemo object internals:
  11. OFFSET SIZE TYPE DESCRIPTION VALUE
  12. (object header) af ( ) (-)
  13. (object header) f6 7f ( ) ()
  14. (object header) d6 f8 ( ) (-)
  15. (loss due to the next object alignment)
  16. Instance size: bytes
  17. Space losses: bytes internal + bytes external = bytes total
  18.  
  19. 2t2 i= get()预期是无锁 com.boke.TestDemo object internals:
  20. OFFSET SIZE TYPE DESCRIPTION VALUE
  21. (object header) ( ) ()
  22. (object header) ( ) ()
  23. (object header) d6 f8 ( ) (-)
  24. (loss due to the next object alignment)
  25. Instance size: bytes
  26. Space losses: bytes internal + bytes external = bytes total
  27.  
  28. t2 i= get(i) 预期轻量级锁 com.boke.TestDemo object internals:
  29. OFFSET SIZE TYPE DESCRIPTION VALUE
  30. (object header) ( ) ()
  31. (object header) ( ) ()
  32. (object header) d6 f8 ( ) (-)
  33. (loss due to the next object alignment)
  34. Instance size: bytes
  35. Space losses: bytes internal + bytes external = bytes total
  36.  
  37. t2 i= get()预期是无锁10com.boke.TestDemo object internals:
  38. OFFSET SIZE TYPE DESCRIPTION VALUE
  39. (object header) ( ) ()
  40. (object header) ( ) ()
  41. (object header) d6 f8 ( ) (-)
  42. (loss due to the next object alignment)
  43. Instance size: bytes
  44. Space losses: bytes internal + bytes external = bytes total
  45.  
  46. t2 i= get(i) 满足重偏向条件20 预期偏向锁 19com.boke.TestDemo object internals:
  47. OFFSET SIZE TYPE DESCRIPTION VALUE
  48. (object header) ae ( ) (-)
  49. (object header) f6 7f ( ) ()
  50. (object header) d6 f8 ( ) (-)
  51. (loss due to the next object alignment)
  52. Instance size: bytes
  53. Space losses: bytes internal + bytes external = bytes total
  54.  
  55. t2 i= get(i) 满足重偏向条件20 但后面的对象没有被加锁,所以依旧偏向t1 19com.boke.TestDemo object internals:
  56. OFFSET SIZE TYPE DESCRIPTION VALUE
  57. (object header) af ( ) (-)
  58. (object header) f6 7f ( ) ()
  59. (object header) d6 f8 ( ) (-)
  60. (loss due to the next object alignment)
  61. Instance size: bytes
  62. Space losses: bytes internal + bytes external = bytes total
  63.  
  64. t2 i= 满足偏向条件之后,之前被设置为无锁状态的对象,不可偏向,这里使用的是轻量级锁 get()预期是轻量级锁 com.boke.TestDemo object internals:
  65. OFFSET SIZE TYPE DESCRIPTION VALUE
  66. (object header) ( ) ()
  67. (object header) ( ) ()
  68. (object header) d6 f8 ( ) (-)
  69. (loss due to the next object alignment)
  70. Instance size: bytes
  71. Space losses: bytes internal + bytes external = bytes total
接下来我们分析两个批量偏向撤销的相关案例(禁止偏向锁延迟的情况下:-XX:+UseBiasedLocking -XX:BiasedLockingStartupDelay=0):
案例一:
  1. public class TestDemo {
  2. }
  3.  
  4. public class DemoExample6 {
  5. public static void main(String[] args) throws InterruptedException {
  6. test2();
  7. }
  8.  
  9. /**
  10. * 证明偏量偏向撤销
  11. * @throws InterruptedException
  12. */
  13. public static void test2() throws InterruptedException {
  14. List<TestDemo> list = new ArrayList<TestDemo>();
  15. for (int i = ; i < ; i++) {
  16. list.add(new TestDemo());
  17. }
  18. Thread t1 = new Thread(()->{
  19. System.out.println("加锁前 get(0) 应该是无锁可偏向 "+ClassLayout.parseInstance(list.get()).toPrintable());
  20. for (TestDemo a:list ) {
  21. synchronized (a){
  22. System.out.print("加锁 >");
  23. }
  24. }
  25. System.out.println();
  26. System.out.println("加锁后 get(0) 应该是偏向锁"+ClassLayout.parseInstance(list.get()).toPrintable());
  27. try {
  28. TimeUnit.SECONDS.sleep();//这里不让线程死,防止线程ID复用
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. });
  33. t1.start();
  34. TimeUnit.SECONDS.sleep();
  35. Thread t2 = new Thread(()->{
  36. for (int i = ; i < ; i++) {
  37. TestDemo a = list.get(i);
  38. synchronized (a){
  39. System.out.println(Thread.currentThread().getId()+"加锁 >");
  40. }
  41. try {
  42. TimeUnit.MILLISECONDS.sleep();
  43. } catch (InterruptedException e) {
  44. e.printStackTrace();
  45. }
  46. if (i==){//这里刚好是第19个上锁的(同样是第19个偏向锁升级的)
  47. System.out.println();
  48. System.out.println("加锁后 get(9) 应该是无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  49. }
  50. if (i==){//这里刚好是第21个上锁的
  51. System.out.println();
  52. System.out.println("加锁后 get(10) 应该是偏向锁 偏向t2 "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  53. }
  54. if (i==){//50开始升级为轻量级锁(同样是第21个偏向锁升级的)
  55. System.out.println();
  56. System.out.println("加锁后 get(50) 无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  57. }
  58. if (i==){//60(同样是第39个偏向锁升级的)
  59. System.out.println();
  60. System.out.println("加锁后 get(59) 无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  61. }
  62. if (i==){//69(同样是第59个偏向锁升级的)
  63. System.out.println();
  64. System.out.println("加锁后 get(69) 无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get(i)).toPrintable());
  65. TestDemo a1 = new TestDemo();
  66. synchronized (a1){
  67. System.out.println("偏向撤销发生后的该类新建的对象都不会再偏向任何线程 "+ClassLayout.parseInstance(a1).toPrintable());
  68. }
  69. }
  70. }
  71. });
  72.  
  73. Thread t3 = new Thread(()->{
  74. for (int i = ; i >= ; i--) {
  75. TestDemo a = list.get(i);
  76. synchronized (a){
  77. System.out.println(Thread.currentThread().getId()+"加锁 >");
  78. }
  79. try {
  80. TimeUnit.MILLISECONDS.sleep();
  81. } catch (InterruptedException e) {
  82. e.printStackTrace();
  83. }
  84. /**
  85. * 重点:重偏向撤销
  86. */
  87. if (i==){//40升级为轻量级锁(同样是第40个偏向锁升级的,这时候发生偏向撤销)
  88. System.out.println();
  89. System.out.println("加锁后 get("+i+") 应该是无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get()).toPrintable());
  90. TestDemo a1 = new TestDemo();
  91. synchronized (a1){
  92. System.out.println("偏向撤销发生后的该类新建的对象都不会再偏向任何线程 "+ClassLayout.parseInstance(a1).toPrintable());
  93. }
  94. }
  95. if (i==){//39升级为轻量级锁(同样是第42个偏向锁升级的)
  96. System.out.println();
  97. System.out.println("加锁后 get("+i+") 应该是无锁(轻量级锁释放) "+ClassLayout.parseInstance(list.get()).toPrintable());
  98. TestDemo a1 = new TestDemo();
  99. synchronized (a1){
  100. System.out.println("偏向撤销发生后的该类新建的对象都不会再偏向任何线程 "+ClassLayout.parseInstance(a1).toPrintable());
  101. }
  102. }
  103. }
  104. });
  105. t2.start();
  106. TimeUnit.MILLISECONDS.sleep();
  107. t3.start();
  108. }
  109. }  
运行结果(截取部分):
  1. 加锁前 get() 应该是无锁可偏向 com.boke.TestDemo object internals:
  2. OFFSET SIZE TYPE DESCRIPTION VALUE
  3. (object header) ( ) ()
  4. (object header) ( ) ()
  5. (object header) c1 f8 ( ) (-)
  6. (loss due to the next object alignment)
  7. Instance size: bytes
  8. Space losses: bytes internal + bytes external = bytes total
  9.  
  10. 加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
  11.  
  12. 加锁后 get() 应该是偏向锁com.boke.TestDemo object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. (object header) e0 ( ) ()
  15. (object header) b1 7f ( ) ()
  16. (object header) c1 f8 ( ) (-)
  17. (loss due to the next object alignment)
  18. Instance size: bytes
  19. Space losses: bytes internal + bytes external = bytes total
  20.  
  21. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  22. OFFSET SIZE TYPE DESCRIPTION VALUE
  23. (object header) ( ) ()
  24. (object header) ( ) ()
  25. (object header) c1 f8 ( ) (-)
  26. (loss due to the next object alignment)
  27. Instance size: bytes
  28. Space losses: bytes internal + bytes external = bytes total
  29.  
  30. 15加锁 >
  31.  
  32. 加锁后 get() 应该是偏向锁 偏向t3com.boke.TestDemo object internals:
  33. OFFSET SIZE TYPE DESCRIPTION VALUE
  34. (object header) 0c ( ) ()
  35. (object header) b1 7f ( ) ()
  36. (object header) c1 f8 ( ) (-)
  37. (loss due to the next object alignment)
  38. Instance size: bytes
  39. Space losses: bytes internal + bytes external = bytes total
  40.  
  41. 加锁后 get() 应该是偏向锁 偏向t2 com.boke.TestDemo object internals:
  42. OFFSET SIZE TYPE DESCRIPTION VALUE
  43. (object header) b1 0a ( ) ()
  44. (object header) b1 7f ( ) ()
  45. (object header) c1 f8 ( ) (-)
  46. (loss due to the next object alignment)
  47. Instance size: bytes
  48. Space losses: bytes internal + bytes external = bytes total
  49.  
  50. 15加锁 >
  51.  
  52. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  53. OFFSET SIZE TYPE DESCRIPTION VALUE
  54. (object header) ( ) ()
  55. (object header) ( ) ()
  56. (object header) c1 f8 ( ) (-)
  57. (loss due to the next object alignment)
  58. Instance size: bytes
  59. Space losses: bytes internal + bytes external = bytes total
  60.  
  61. 加锁后 get() 无锁(轻量级锁释放) com.boke.TestDemo object internals:
  62. OFFSET SIZE TYPE DESCRIPTION VALUE
  63. (object header) ( ) ()
  64. (object header) ( ) ()
  65. (object header) c1 f8 ( ) (-)
  66. (loss due to the next object alignment)
  67. Instance size: bytes
  68. Space losses: bytes internal + bytes external = bytes total
  69.  
  70. 15加锁 >
  71.  
  72. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  73. OFFSET SIZE TYPE DESCRIPTION VALUE
  74. (object header) ( ) ()
  75. (object header) ( ) ()
  76. (object header) c1 f8 ( ) (-)
  77. (loss due to the next object alignment)
  78. Instance size: bytes
  79. Space losses: bytes internal + bytes external = bytes total
  80.  
  81. 加锁后 get() 无锁(轻量级锁释放) com.boke.TestDemo object internals:
  82. OFFSET SIZE TYPE DESCRIPTION VALUE
  83. (object header) ( ) ()
  84. (object header) ( ) ()
  85. (object header) c1 f8 ( ) (-)
  86. (loss due to the next object alignment)
  87. Instance size: bytes
  88. Space losses: bytes internal + bytes external = bytes total
  89.  
  90. 15加锁 >
  91.  
  92. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  93. OFFSET SIZE TYPE DESCRIPTION VALUE
  94. (object header) ( ) ()
  95. (object header) ( ) ()
  96. (object header) c1 f8 ( ) (-)
  97. (loss due to the next object alignment)
  98. Instance size: bytes
  99. Space losses: bytes internal + bytes external = bytes total
  100.  
  101. 偏向撤销发生后的该类新建的对象都不会再偏向任何线程 com.boke.TestDemo object internals:
  102. OFFSET SIZE TYPE DESCRIPTION VALUE
  103. (object header) a6 ( ) ()
  104. (object header) ( ) ()
  105. (object header) c1 f8 ( ) (-)
  106. (loss due to the next object alignment)
  107. Instance size: bytes
  108. Space losses: bytes internal + bytes external = bytes total
  109.  
  110. 加锁后 get() 无锁(轻量级锁释放) com.boke.TestDemo object internals:
  111. OFFSET SIZE TYPE DESCRIPTION VALUE
  112. (object header) ( ) ()
  113. (object header) ( ) ()
  114. (object header) c1 f8 ( ) (-)
  115. (loss due to the next object alignment)
  116. Instance size: bytes
  117. Space losses: bytes internal + bytes external = bytes total
  118.  
  119. 偏向撤销发生后的该类新建的对象都不会再偏向任何线程 com.boke.TestDemo object internals:
  120. OFFSET SIZE TYPE DESCRIPTION VALUE
  121. (object header) e8 ( ) ()
  122. (object header) ( ) ()
  123. (object header) c1 f8 ( ) (-)
  124. (loss due to the next object alignment)
  125. Instance size: bytes
  126. Space losses: bytes internal + bytes external = bytes total
  127.  
  128. 15加锁 >
  129.  
  130. 加锁后 get() 应该是无锁(轻量级锁释放) com.boke.TestDemo object internals:
  131. OFFSET SIZE TYPE DESCRIPTION VALUE
  132. (object header) ( ) ()
  133. (object header) ( ) ()
  134. (object header) c1 f8 ( ) (-)
  135. (loss due to the next object alignment)
  136. Instance size: bytes
  137. Space losses: bytes internal + bytes external = bytes total
  138.  
  139. 偏向撤销发生后的该类新建的对象都不会再偏向任何线程 com.boke.TestDemo object internals:
  140. OFFSET SIZE TYPE DESCRIPTION VALUE
  141. (object header) a6 ( ) ()
  142. (object header) ( ) ()
  143. (object header) c1 f8 ( ) (-)
  144. (loss due to the next object alignment)
  145. Instance size: bytes
  146. Space losses: bytes internal + bytes external = bytes total
 
案例二:

 

  1. public class TestDemo {
  2. }
  3. public class DemoExample8 {
  4. public static void main(String[] args) throws Exception {
  5. List<TestDemo> list = new ArrayList<>();
  6. List<TestDemo> list2 = new ArrayList<>();
  7. List<TestDemo> list3 = new ArrayList<>();
  8. for (int i = ; i < ; i++) {
  9. list.add(new TestDemo());
  10. list2.add(new TestDemo());
  11. list3.add(new TestDemo());
  12. }
  13. //偏向锁
  14. System.out.println("初始状态" + + ClassLayout.parseClass(TestDemo.class).toPrintable());
  15.  
  16. Thread t1 = new Thread() {
  17. String name = "";
  18. public void run() {
  19. System.out.printf(name);
  20. for (TestDemo a : list) {
  21. synchronized (a) {
  22. if (a == list.get()) {
  23. //偏向锁
  24. System.out.println("t1 预期是偏向锁" + + ClassLayout.parseInstance(a).toPrintable());
  25. }
  26. }
  27. }
  28. try {
  29. Thread.sleep();
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. };
  35. t1.start();
  36. Thread.sleep();
  37. //偏向锁
  38. System.out.println("main 预期是偏向锁" + + ClassLayout.parseInstance(list.get()).toPrintable());
  39. Thread t2 = new Thread() {
  40. String name = "";
  41. public void run() {
  42. System.out.printf(name);
  43. for (int i = ; i < ; i++) {
  44. TestDemo a = list.get(i);
  45. synchronized (a) {
  46. if (a == list.get()) {
  47. System.out.println("t2 i=10 get(1)预期是无锁" + ClassLayout.parseInstance(list.get()).toPrintable());//偏向锁
  48. System.out.println("t2 i=10 get(10) 预期轻量级锁 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  49. }
  50. if (a == list.get()) {
  51. System.out.println("t2 i=19 get(10)预期是无锁" + + ClassLayout.parseInstance(list.get()).toPrintable());//偏向锁
  52. System.out.println("t2 i=19 get(19) 满足重偏向条件20 预期偏向锁 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  53. System.out.println("类的对象累计撤销达到20");
  54. }
  55. }
  56. }
  57. try {
  58. Thread.sleep();
  59. } catch (InterruptedException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. };
  64. t2.start();
  65. Thread.sleep();
  66.  
  67. Thread t3 = new Thread() {
  68. String name = "";
  69. public void run() {
  70. System.out.printf(name);
  71. for (TestDemo a : list2) {
  72. synchronized (a) {
  73. if (a == list2.get()) {
  74. System.out.println("t3 预期是偏向锁" + + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  75. }
  76. }
  77. }
  78. try {
  79. Thread.sleep();
  80. } catch (InterruptedException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. };
  85. t3.start();
  86. Thread.sleep();
  87.  
  88. Thread t4 = new Thread() {
  89. String name = "";
  90. public void run() {
  91. System.out.printf(name);
  92. for (int i = ; i < ; i++) {
  93. TestDemo a = list2.get(i);
  94. synchronized (a) {
  95. if (a == list2.get()) {
  96. System.out.println("t4 i=10 get(1)预期是无锁" + ClassLayout.parseInstance(list2.get()).toPrintable());//偏向锁
  97. System.out.println("t4 i=10 get(10) 当前不满足重偏向条件 20 预期轻量级锁 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  98. }
  99. if (a == list2.get()) {
  100. System.out.println("t4 i=19 get(10)预期是无锁" + + ClassLayout.parseInstance(list2.get()).toPrintable());//偏向锁
  101. System.out.println("t4 i=19 get(19) 当前满足重偏向条件 20 但A类的对象累计撤销达到40 预期轻量级锁 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  102. System.out.println("类的对象累计撤销达到40");
  103. }
  104. if (a == list2.get()) {
  105. System.out.println("t4 i=20 get(20) 当前满足重偏向条件 20 预期轻量级锁 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  106. }
  107. }
  108. }
  109. }
  110. };
  111. t4.start();
  112. Thread.sleep();
  113. System.out.println("main 预期是偏向锁" + + ClassLayout.parseInstance(list3.get()).toPrintable());//偏向锁
  114. Thread t5 = new Thread() {
  115. String name = "";
  116. public void run() {
  117. System.out.printf(name);
  118. for (TestDemo a : list3) {
  119. synchronized (a) {
  120. if (a == list3.get()) {
  121. System.out.println("t5 预期是轻量级锁,类的对象累计撤销达到40 不可以用偏向锁了" + + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  122. }
  123. }
  124. }
  125. try {
  126. Thread.sleep();
  127. } catch (InterruptedException e) {
  128. e.printStackTrace();
  129. }
  130. }
  131. };
  132. t5.start();
  133. Thread.sleep();
  134. System.out.println("main 预期是偏向锁" + + ClassLayout.parseInstance(list.get()).toPrintable());//偏向锁
  135.  
  136. Thread t6 = new Thread() {
  137. String name = "";
  138. public void run() {
  139. System.out.printf(name);
  140. for (int i = ; i < ; i++) {
  141. TestDemo a = list3.get(i);
  142. synchronized (a) {
  143. if (a == list3.get()) {
  144. System.out.println("t6 i=10 get(1)预期是无锁" + ClassLayout.parseInstance(list3.get()).toPrintable());//偏向锁
  145. System.out.println("t6 i=10 get(10) 预期轻量级锁 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  146. }
  147. if (a == list3.get()) {
  148. System.out.println("t6 i=19 get(10)预期是无锁" + + ClassLayout.parseInstance(list3.get()).toPrintable());//偏向锁
  149. System.out.println("t6 i=19 get(19) 满足重偏向条件20 但类的对象累计撤销达到40 不可以用偏向锁了 " + i + ClassLayout.parseInstance(a).toPrintable());//偏向锁
  150. }
  151. }
  152. }
  153.  
  154. try {
  155. Thread.sleep();
  156. } catch (InterruptedException e) {
  157. e.printStackTrace();
  158. }
  159. }
  160. };
  161. t6.start();
  162. Thread.sleep();
  163.  
  164. System.out.println("由于撤销锁次数达到默认的 BiasedLockingBulkRevokeThreshold=40 这里实例化的对象 是无锁状态" + ClassLayout.parseInstance(new TestDemo()).toPrintable());//偏向锁
  165.      System.out.println("撤销偏向后状态" + + ClassLayout.parseInstance(new TestDemo()).toPrintable());//偏向锁
  166.   }
  167. }
运行结果:
  1. 初始状态10 com.boke.TestDemo object internals:
  2. OFFSET SIZE TYPE DESCRIPTION VALUE
  3. (object header) N/A
  4. (loss due to the next object alignment)
  5. Instance size: bytes
  6. Space losses: bytes internal + bytes external = bytes total
  7.  
  8. 1t1 预期是偏向锁10 com.boke.TestDemo object internals:
  9. OFFSET SIZE TYPE DESCRIPTION VALUE
  10. (object header) e0 8e ( ) (-)
  11. (object header) ec 7f ( ) ()
  12. (object header) bf c3 f8 ( ) (-)
  13. (loss due to the next object alignment)
  14. Instance size: bytes
  15. Space losses: bytes internal + bytes external = bytes total
  16.  
  17. main 预期是偏向锁10 com.boke.TestDemo object internals:
  18. OFFSET SIZE TYPE DESCRIPTION VALUE
  19. (object header) e0 8e ( ) (-)
  20. (object header) ec 7f ( ) ()
  21. (object header) bf c3 f8 ( ) (-)
  22. (loss due to the next object alignment)
  23. Instance size: bytes
  24. Space losses: bytes internal + bytes external = bytes total
  25.  
  26. 2t2 i= get()预期是无锁com.boke.TestDemo object internals:
  27. OFFSET SIZE TYPE DESCRIPTION VALUE
  28. (object header) ( ) ()
  29. (object header) ( ) ()
  30. (object header) bf c3 f8 ( ) (-)
  31. (loss due to the next object alignment)
  32. Instance size: bytes
  33. Space losses: bytes internal + bytes external = bytes total
  34.  
  35. t2 i= get() 预期轻量级锁 com.boke.TestDemo object internals:
  36. OFFSET SIZE TYPE DESCRIPTION VALUE
  37. (object header) 7a ( ) ()
  38. (object header) ( ) ()
  39. (object header) bf c3 f8 ( ) (-)
  40. (loss due to the next object alignment)
  41. Instance size: bytes
  42. Space losses: bytes internal + bytes external = bytes total
  43.  
  44. t2 i= get()预期是无锁10 com.boke.TestDemo object internals:
  45. OFFSET SIZE TYPE DESCRIPTION VALUE
  46. (object header) ( ) ()
  47. (object header) ( ) ()
  48. (object header) bf c3 f8 ( ) (-)
  49. (loss due to the next object alignment)
  50. Instance size: bytes
  51. Space losses: bytes internal + bytes external = bytes total
  52.  
  53. t2 i= get() 满足重偏向条件20 预期偏向锁 19com.boke.TestDemo object internals:
  54. OFFSET SIZE TYPE DESCRIPTION VALUE
  55. (object header) ( ) (-)
  56. (object header) ec 7f ( ) ()
  57. (object header) bf c3 f8 ( ) (-)
  58. (loss due to the next object alignment)
  59. Instance size: bytes
  60. Space losses: bytes internal + bytes external = bytes total
  61.  
  62. 类的对象累计撤销达到20
  63. 3t3 预期是偏向锁10com.boke.TestDemo object internals:
  64. OFFSET SIZE TYPE DESCRIPTION VALUE
  65. (object header) ( ) (-)
  66. (object header) ec 7f ( ) ()
  67. (object header) bf c3 f8 ( ) (-)
  68. (loss due to the next object alignment)
  69. Instance size: bytes
  70. Space losses: bytes internal + bytes external = bytes total
  71.  
  72. 4t4 i= get()预期是无锁com.boke.TestDemo object internals:
  73. OFFSET SIZE TYPE DESCRIPTION VALUE
  74. (object header) ( ) ()
  75. (object header) ( ) ()
  76. (object header) bf c3 f8 ( ) (-)
  77. (loss due to the next object alignment)
  78. Instance size: bytes
  79. Space losses: bytes internal + bytes external = bytes total
  80.  
  81. t4 i= get() 当前不满足重偏向条件 预期轻量级锁 10com.boke.TestDemo object internals:
  82. OFFSET SIZE TYPE DESCRIPTION VALUE
  83. (object header) f9 9a ( ) ()
  84. (object header) ( ) ()
  85. (object header) bf c3 f8 ( ) (-)
  86. (loss due to the next object alignment)
  87. Instance size: bytes
  88. Space losses: bytes internal + bytes external = bytes total
  89.  
  90. t4 i= get()预期是无锁10com.boke.TestDemo object internals:
  91. OFFSET SIZE TYPE DESCRIPTION VALUE
  92. (object header) ( ) ()
  93. (object header) ( ) ()
  94. (object header) bf c3 f8 ( ) (-)
  95. (loss due to the next object alignment)
  96. Instance size: bytes
  97. Space losses: bytes internal + bytes external = bytes total
  98.  
  99. t4 i= get() 当前满足重偏向条件 A类的对象累计撤销达到40 预期轻量级锁 19com.boke.TestDemo object internals:
  100. OFFSET SIZE TYPE DESCRIPTION VALUE
  101. (object header) f9 9a ( ) ()
  102. (object header) ( ) ()
  103. (object header) bf c3 f8 ( ) (-)
  104. (loss due to the next object alignment)
  105. Instance size: bytes
  106. Space losses: bytes internal + bytes external = bytes total
  107.  
  108. 类的对象累计撤销达到40
  109. t4 i= get() 当前满足重偏向条件 预期轻量级锁 20com.boke.TestDemo object internals:
  110. OFFSET SIZE TYPE DESCRIPTION VALUE
  111. (object header) f9 9a ( ) ()
  112. (object header) ( ) ()
  113. (object header) bf c3 f8 ( ) (-)
  114. (loss due to the next object alignment)
  115. Instance size: bytes
  116. Space losses: bytes internal + bytes external = bytes total
  117.  
  118. main 预期是偏向锁10com.boke.TestDemo object internals:
  119. OFFSET SIZE TYPE DESCRIPTION VALUE
  120. (object header) ( ) ()
  121. (object header) ( ) ()
  122. (object header) bf c3 f8 ( ) (-)
  123. (loss due to the next object alignment)
  124. Instance size: bytes
  125. Space losses: bytes internal + bytes external = bytes total
  126.  
  127. 5t5 预期是轻量级锁,A类的对象累计撤销达到40 不可以用偏向锁了10com.boke.TestDemo object internals:
  128. OFFSET SIZE TYPE DESCRIPTION VALUE
  129. (object header) f9 9a ( ) ()
  130. (object header) ( ) ()
  131. (object header) bf c3 f8 ( ) (-)
  132. (loss due to the next object alignment)
  133. Instance size: bytes
  134. Space losses: bytes internal + bytes external = bytes total
  135.  
  136. main 预期是偏向锁10com.boke.TestDemo object internals:
  137. OFFSET SIZE TYPE DESCRIPTION VALUE
  138. (object header) ( ) ()
  139. (object header) ( ) ()
  140. (object header) bf c3 f8 ( ) (-)
  141. (loss due to the next object alignment)
  142. Instance size: bytes
  143. Space losses: bytes internal + bytes external = bytes total
  144.  
  145. 6t6 i= get()预期是无锁com.boke.TestDemo object internals:
  146. OFFSET SIZE TYPE DESCRIPTION VALUE
  147. (object header) ( ) ()
  148. (object header) ( ) ()
  149. (object header) bf c3 f8 ( ) (-)
  150. (loss due to the next object alignment)
  151. Instance size: bytes
  152. Space losses: bytes internal + bytes external = bytes total
  153.  
  154. t6 i= get() 预期轻量级锁 10com.boke.TestDemo object internals:
  155. OFFSET SIZE TYPE DESCRIPTION VALUE
  156. (object header) ab ( ) ()
  157. (object header) ( ) ()
  158. (object header) bf c3 f8 ( ) (-)
  159. (loss due to the next object alignment)
  160. Instance size: bytes
  161. Space losses: bytes internal + bytes external = bytes total
  162.  
  163. t6 i= get()预期是无锁10com.boke.TestDemo object internals:
  164. OFFSET SIZE TYPE DESCRIPTION VALUE
  165. (object header) ( ) ()
  166. (object header) ( ) ()
  167. (object header) bf c3 f8 ( ) (-)
  168. (loss due to the next object alignment)
  169. Instance size: bytes
  170. Space losses: bytes internal + bytes external = bytes total
  171.  
  172. t6 i= get() 满足重偏向条件20 A类的对象累计撤销达到40 不可以用偏向锁了 19com.boke.TestDemo object internals:
  173. OFFSET SIZE TYPE DESCRIPTION VALUE
  174. (object header) ab ( ) ()
  175. (object header) ( ) ()
  176. (object header) bf c3 f8 ( ) (-)
  177. (loss due to the next object alignment)
  178. Instance size: bytes
  179. Space losses: bytes internal + bytes external = bytes total
  180.  
  181. 由于类撤销锁次数达到默认的 BiasedLockingBulkRevokeThreshold= 这里实例化的对象 是无锁状态com.boke.TestDemo object internals:
  182. OFFSET SIZE TYPE DESCRIPTION VALUE
  183. (object header) ( ) ()
  184. (object header) ( ) ()
  185. (object header) bf c3 f8 ( ) (-)
  186. (loss due to the next object alignment)
  187. Instance size: bytes
  188. Space losses: bytes internal + bytes external = bytes total
  189.  
  190. 撤销偏向后状态10com.boke.TestDemo object internals:
  191. OFFSET SIZE TYPE DESCRIPTION                     VALUE
  192.              (object header)                ( ) ()
  193.               (object header)                ( ) ()
  194.              (object header)                bf c3 f8 ( ) (-)
  195.             (loss due to the next object alignment)
  196. Instance size: bytes
  197. Space losses: bytes internal + bytes external = bytes total
以上案例证实了偏向锁的批量重偏向和批量撤销,接下来我们讲解轻量级锁;

轻量级锁:

  • 当锁是偏向锁的时候,被另外的线程所访问,偏向锁就会升级为轻量级锁,其他线程会通过自旋的形式尝试获取锁,不会阻塞,从而提高性能。
  • 在代码进入同步块的时候,如果同步对象锁状态为无锁状态(锁标志位为“01”状态,是否为偏向锁为“0”),虚拟机首先将在当前线程的栈帧中建立一个名为锁记录(Lock Record)的空间,用于存储锁对象目前的Mark Word的拷贝,然后拷贝对象头中的Mark Word复制到锁记录中。
  • 拷贝成功后,虚拟机将使用CAS操作尝试将对象的Mark Word更新为指向Lock Record的指针,并将Lock Record里的owner指针指向对象的Mark Word。
  • 如果这个更新动作成功了,那么这个线程就拥有了该对象的锁,并且对象Mark Word的锁标志位设置为“00”,表示此对象处于轻量级锁定状态。
  • 如果轻量级锁的更新操作失败了,虚拟机首先会检查对象的Mark Word是否指向当前线程的栈帧,如果是就说明当前线程已经拥有了这个对象的锁,那就可以直接进入同步块继续执行,否则说明多个线程竞争锁。
  • 若当前只有一个等待线程,则该线程通过自旋进行等待。但是当自旋超过一定的次数,或者一个线程在持有锁,一个在自旋,又有第三个来访时,轻量级锁升级为重量级锁。
  • 多个线程在不同的时间段请求同一把锁,也就是说没有锁竞争。针对这种情形,Java 虚拟机采用了轻量级锁,来避免重量级锁的阻塞以及唤醒
  • 在没有锁竞争的前提下,减少传统锁使用OS互斥量产生的性能损耗
  • 在竞争激烈时,轻量级锁会多做很多额外操作,导致性能下降
  • 可以认为两个线程交替执行的情况下请求同一把锁
分析一个由偏向锁膨胀成轻量级锁的案例:
  1. public class TestDemo {
  2. }
  3. public class DemoExample9 {
  4. public static void main(String[] args) throws Exception {
  5. TestDemo testDemo = new TestDemo();
  6.  
  7. //子线程
  8. Thread t1 = new Thread(){
  9. @Override
  10. public void run() {
  11. synchronized (testDemo){
  12. System.out.println("t1 lock ing");
  13. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  14. }
  15. }
  16. };
  17.  
  18. t1.join();
  19.  
  20. //主线程
  21. synchronized (testDemo){
  22. System.out.println("main lock ing");
  23. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  24. }
  25.  
  26. }
  27. }
运行结果(两个线程交替执行的情况下):
  1. main lock ing
  2. com.boke.TestDemo object internals:
  3. OFFSET SIZE TYPE DESCRIPTION VALUE
  4. (object header) e8 ( ) ()
  5. (object header) ( ) ()
  6. (object header) a0 c1 f8 ( ) (-)
  7. (loss due to the next object alignment)
  8. Instance size: bytes
  9. Space losses: bytes internal + bytes external = bytes total

重量级锁:

  • 多个线程竞争同一个锁的时候,虚拟机会阻塞加锁失败的线程,并且在目标锁被释放的时候,唤醒这些线程;
  • Java 线程的阻塞以及唤醒,都是依靠操作系统来完成的:os pthread_mutex_lock() ;
  • 升级为重量级锁时,锁标志的状态值变为“10”,此时Mark Word中存储的是指向重量级锁的指针,此时等待锁的线程都会进入阻塞状态

分析一个由轻量级锁膨胀成重量级锁的案例:

  1. public class TestDemo {
  2. }
  3. public class DemoExample9 {
  4. public static void main(String[] args) throws Exception {
  5. TestDemo testDemo = new TestDemo();
  6.  
  7. Thread t1 = new Thread(){
  8. @Override
  9. public void run() {
  10. synchronized (testDemo){
  11. System.out.println("t1 lock ing");
  12. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  13. }
  14. }
  15. };
  16.  
  17. t1.start();
  18.  
  19. synchronized (testDemo){
  20. System.out.println("main lock ing");
  21. System.out.println(ClassLayout.parseInstance(testDemo).toPrintable());
  22. }
  23. }
  24. }

运行结果:

  1. main lock ing
  2. com.boke.TestDemo object internals:
  3. OFFSET SIZE TYPE DESCRIPTION VALUE
  4. (object header) 5a ad b0 ( ) (-)
  5. (object header) cf 7f ( ) ()
  6. (object header) a0 c1 f8 ( ) (-)
  7. (loss due to the next object alignment)
  8. Instance size: bytes
  9. Space losses: bytes internal + bytes external = bytes total
  10.  
  11. t1 lock ing
  12. com.boke.TestDemo object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. (object header) 5a ad b0 ( ) (-)
  15. (object header) cf 7f ( ) ()
  16. (object header) a0 c1 f8 ( ) (-)
  17. (loss due to the next object alignment)

我们再来说一下Java 虚拟机是怎么区分轻量级锁和重量级锁的:

  • 当进行加锁操作时,Java 虚拟机会判断是否已经是重量级锁。如果不是,它会在当前线程的当前栈桢中划出一块空间,作为该锁的锁记录,并且将锁对象的标记字段复制到该锁记录中。
  • 然后,Java 虚拟机会尝试用 CAS(compare-and-swap)操作替换锁对象的标记字段。这里解释一下,CAS 是一个原子操作,它会比较目标地址的值是否和期望值相等,如果相等,则替换为一个新的值。
  • 假设当前锁对象的标记字段为 X…XYZ,Java 虚拟机会比较该字段是否为 X…X01。如果是,则替换为刚才分配的锁记录的地址。由于内存对齐的缘故,它的最后两位为 00。此时,该线程已成功获得这把锁,可以继续执行了。
  • 如果不是 X…X01,那么有两种可能。第一,该线程重复获取同一把锁。此时,Java 虚拟机会将锁记录清零,以代表该锁被重复获取。第二,其他线程持有该锁。此时,Java 虚拟机会将这把锁膨胀为重量级锁,并且阻塞当前线程。
  • 当进行解锁操作时,如果当前锁记录(你可以将一个线程的所有锁记录想象成一个栈结构,每次加锁压入一条锁记录,解锁弹出一条锁记录,当前锁记录指的便是栈顶的锁记录)的值为 0,则代表重复进入同一把锁,直接返回即可。
  • 否则,Java 虚拟机会尝试用 CAS 操作,比较锁对象的标记字段的值是否为当前锁记录的地址。如果是,则替换为锁记录中的值,也就是锁对象原本的标记字段。此时,该线程已经成
  • 功释放这把锁。
  • 如果不是,则意味着这把锁已经被膨胀为重量级锁。此时,Java 虚拟机会进入重量级锁的释放过程,唤醒因竞争该锁而被阻塞了的线程

 
到此为止本篇就讲完了锁的膨胀过程

 

总结一下

  1. 偏向锁只会在第一次请求时采用 CAS 操作,在锁对象的标记字段中记录下当前线程的地址。在之后的运行过程中,持有该偏向锁的线程的加锁操作将直接返回。它针对的是锁仅会被同一线程持有的情况。
  2. 轻量级锁采用 CAS 操作,将锁对象的标记字段替换为一个指针,指向当前线程栈上的一块空间,存储着锁对象原本的标记字段。它针对的是多个线程在不同时间段申请同一把锁的情况。
  3. 重量级锁会阻塞、唤醒请求加锁的线程。它针对的是多个线程同时竞争同一把锁的情况。Java 虚拟机采取了自适应自旋,来避免线程在面对非常小的 synchronized 代码块时,仍会被阻塞、唤醒的情况。
 
 
说完了锁的膨胀过程,那么会不会有锁的降级呢?
 
我在hotspot源码中找到了这样的注释:
  1. // We create a list of in-use monitors for each thread.
  2. //
  3. // deflate_thread_local_monitors() scans a single thread's in-use list, while
  4. // deflate_idle_monitors() scans only a global list of in-use monitors which
  5. // is populated only as a thread dies (see omFlush()).
  6. //
  7. // These operations are called at all safepoints, immediately after mutators
  8. // are stopped, but before any objects have moved. Collectively they traverse
  9. // the population of in-use monitors, deflating where possible. The scavenged
  10. // monitors are returned to the monitor free list.
  11. //
  12. // Beware that we scavenge at *every* stop-the-world point. Having a large
  13. // number of monitors in-use could negatively impact performance. We also want
  14. // to minimize the total # of monitors in circulation, as they incur a small
  15. // footprint penalty.
  16. //
  17. // Perversely, the heap size -- and thus the STW safepoint rate --
  18. // typically drives the scavenge rate. Large heaps can mean infrequent GC,
  19. // which in turn can mean large(r) numbers of objectmonitors in circulation.
  20. // This is an unfortunate aspect of this design.
//大概意思是:锁降级确实是会发生的,当 JVM 进入安全点(SafePoint)的时候,会检查是否有闲置的 Monitor,然后试图进行降级
有兴趣的大佬可以在https://hg.openjdk.java.net/jdk/jdk/file/896e80158d35/src/hotspot/share/runtime/synchronizer.cpp链接中:
研究一下deflate_idle_monitors是分析锁降级逻辑的入口,这部分行为还在进行持续改进,因为其逻辑是在安全点内运行,处理不当可能拖长 JVM 停顿(STW,stop-the-world)的时间。
 
 

synchronized(三) 锁的膨胀过程(锁的升级过程)深入剖析的更多相关文章

  1. android recovery升级过程中掉电处理

    一般在升级过程,都会提示用户,请勿断电,不管是android的STB,TV还是PHONE,或者是其他的终端设备,升级过程,基本上都可以看到“正在升级,请勿断电”,然后有个进度条,显示升级的进度. 但是 ...

  2. java并发笔记之四synchronized 锁的膨胀过程(锁的升级过程)深入剖析

    警告⚠️:本文耗时很长,先做好心理准备,建议PC端浏览器浏览效果更佳. 本篇我们讲通过大量实例代码及hotspot源码分析偏向锁(批量重偏向.批量撤销).轻量级锁.重量级锁及锁的膨胀过程(也就是锁的升 ...

  3. java架构之路(多线程)synchronized详解以及锁的膨胀升级过程

    上几次博客,我们把volatile基本都说完了,剩下的还有我们的synchronized,还有我们的AQS,这次博客我来说一下synchronized的使用和原理. synchronized是jvm内 ...

  4. Synchronized用法原理和锁优化升级过程(面试)

    简介 多线程一直是面试中的重点和难点,无论你现在处于啥级别段位,对synchronized关键字的学习避免不了,这是我的心得体会.下面咱们以面试的思维来对synchronized做一个系统的描述,如果 ...

  5. 详细了解 synchronized 锁升级过程

    前言 首先,synchronized 是什么?我们需要明确的给个定义--同步锁,没错,它就是把锁. 可以用来干嘛?锁,当然当然是用于线程间的同步,以及保护临界区内的资源.我们知道,锁是个非常笼统的概念 ...

  6. JAVA锁的膨胀过程和优化

    首先说一下锁的优化策略. 1,自旋锁 自选锁其实就是在拿锁时发现已经有线程拿了锁,自己如果去拿会阻塞自己,这个时候会选择进行一次忙循环尝试.也就是不停循环看是否能等到上个线程自己释放锁.这个问题是基于 ...

  7. 并发编程:synchronized 锁升级过程的验证

        关于synchronized关键字以及偏向锁.轻量级锁.重量级锁的介绍广大网友已经给出了太多文章和例子,这里就不再重复了,也可点击链接来回顾一下.在这里来实战操作一把,验证JVM是怎么一步一步 ...

  8. JAVA锁的膨胀过程和优化(阿里)

    阿里的人问什么是锁膨胀,答不上来,回来做了总结: 关于锁的膨胀,synchronized的原理参考:深入分析Synchronized原理(阿里面试题) 首先说一下锁的优化策略. 1,自旋锁 自旋锁其实 ...

  9. synchronized优化手段:锁膨胀、锁消除、锁粗化和自适应自旋锁...

    synchronized 在 JDK 1.5 时性能是比较低的,然而在后续的版本中经过各种优化迭代,它的性能也得到了前所未有的提升,上一篇中我们谈到了锁膨胀对 synchronized 性能的提升,然 ...

随机推荐

  1. Cannot use JSX unless the '--jsx' flag is provided.

    在tsx文件中加入html代码后,报错 Cannot use JSX unless the '--jsx' flag is provided. 解决方法: 在tsconfig.json中加入: &qu ...

  2. 题解 【POJ1934】 Trip

    题目意思: 有两个字符串(长度\(<=80\)),按字典序输出它们的最长公共子串的所有情况. 解析 最长公共子序列的长度应该都没问题了吧...有问题请自行百度 但关键是要求出每种情况,还要按字典 ...

  3. jquery blur()函数 语法

    jquery blur()函数 语法 作用:当元素失去焦点时发生 blur 事件.blur() 函数触发 blur 事件,或者如果设置了 function 参数,该函数也可规定当发生 blur 事件时 ...

  4. jQuery文档操作之克隆操作

    语法: $(selector).clone(); 解释:克隆匹配的DOM元素 $("button").click(function(event) { //1.clone():克隆匹 ...

  5. HDU 5894 hannnnah_j’s Biological Test ——(组合数)

    思路来自于:http://blog.csdn.net/lzedo/article/details/52585170. 不过并不需要卢卡斯定理,直接组合数就可以了. 代码如下: #include < ...

  6. Inter IPP 绘图 ippi/ipps

    IPP的资料网上比较少,主要还是参考Inter官网和文档 官方文档ipps.pdf主要是对数据做处理,包括加减乘除.FFT.DFT等 文档ippi.pdf只要是对图像做处理,包括通道转换.图片处理等 ...

  7. C++ this指针的理解

    先要理解class的意思.class应该理解为一种类型,象 int,char一样,是用户自定义的类型.虽然比int char这样build-in类型复杂的多,但首先要理解它们一样是类型.用这个类型可以 ...

  8. mysql基础知识语法汇总整理(一)

    mysql基础知识语法汇总整理(二)   连接数据库操作 /*连接mysql*/ mysql -h 地址 -P 端口 -u 用户名 -p 密码 例如: mysql -u root -p **** /* ...

  9. 08.青蛙跳台阶 Java

    题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果). 思路 暴力枚举(自顶向下递归): 若台阶数小于等于0,返回0: 若台阶 ...

  10. HTML中meta=“viewport”的介绍

    viewport就是浏览器上用来显示网页的那部分区域 layout viewport:整个网页所占据的区域(包括可视也包括不可视的区域)  默认的 visual viewport:网页在浏览器上的可视 ...