synchronize偏向锁底层实现原理

x33g5p2x  于2022-03-04 转载在 其他  
字(7.3k)|赞(0)|评价(0)|浏览(570)

1 偏向锁的意义

无多线程竞争时,减少不必要的轻量级锁执行路径。大多数情况下,锁不仅不存在多线程竞争,而且总是由同一条线程去多次获得锁,为了让线程获得锁的性能代价更低而引入了偏向锁。

偏向锁主要用来优化同一线程多次申请同一个锁的竞争,即当对象被当做同步锁并有一个线程抢到了锁时,则在Mark Word设置该线程的线程ID、是否偏向锁设置1、锁标志位设置01等信息,此时的Mark Word 存储的就是偏向锁状态信息。

在:

  • 创建一个线程并在线程中执行循环监听的场景下
  • 或单线程操作一个线程安全集合时

同一线程每次都需获取和释放锁,每次操作都会发生用户态与内核态的切换。

获取偏向锁的场景:

在自己的线程栈生成一条Lock Record,然后Object Reference指向对象头,此时Lock Record与对象头就建立了联系:

① : 先判断Mard Word的Thread ID是否有值

  • 没有,则表示当前资源没有被其他线程占用,把当前线程ID等信息记录到Mark Word(这需CAS,可能多条线程修改Mark Word,需要保证原子性)

  • 有,则表示当前资源被线程占用,需要判断该线程是不是自己

  • 该线程ID是自己的,则表示可重入,直接获取(此时在自己的线程栈中继续生成一条新的Lock Record)

  • 该线程ID不是自己的,说明出现其他线程竞争,当前持有偏向锁的线程就需要撤销了,即当其他线程尝试获取偏向锁才释放锁

轻量级锁的获取及释放依赖多次的CAS操作,而偏向锁只依赖一次CAS置换ThreadID

一旦出现多个线程竞争时必须撤销偏向锁,所以:

撤销偏向锁消耗的性能必须 < 之前节省下来的CAS原子操作的性能消耗

不然得不偿失!

JDK6默认开启偏向锁,可通过-XX:-UseBiasedLocking禁用偏向锁。

2 偏向锁的获取

偏向锁的入口,synchronizer.cpp 文件的

ObjectSynchronizer::fast_enter

BiasedLocking::revoke_and_rebias实现

2.1 markOop mark = obj->mark()

获取对象的markOop数据mark,即对象头的Mark Word

2.2 判断mark是否为可偏向状态

mark的偏向锁的锁标志位为 01

2.3 判断mark中JavaThread的状态

  • 若指向当前线程,则执行同步代码块
  • 若为空,则走4
  • 若指向其它线程,则走5

2.4 执行CAS原子指令

设置mark中JavaThread为当前线程ID。

若CAS成功,则执行同步代码块,否则走5。

2.5 执行CAS失败

说明当前存在多个线程竞争锁,当达到全局安全点(safepoint),获得偏向锁的线程就会被挂起,撤销偏向锁,并升级为轻量级锁。

升级完成后被阻塞在安全点的线程继续执行同步代码块。

  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. // We can revoke the biases of anonymously-biased objects
  4. // efficiently enough that we should not cause these revocations to
  5. // update the heuristics because doing so may cause unwanted bulk
  6. // revocations (which are expensive) to occur.
  7. // step1
  8. markOop mark = obj->mark();
  9. if (mark->is_biased_anonymously() && !attempt_rebias) {
  10. // We are probably trying to revoke the bias of this object due to
  11. // an identity hash code computation. Try to revoke the bias
  12. // without a safepoint. This is possible if we can successfully
  13. // compare-and-exchange an unbiased header into the mark word of
  14. // the object, meaning that no other thread has raced to acquire
  15. // the bias of the object.
  16. markOop biased_value = mark;
  17. markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
  18. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(unbiased_prototype, obj->mark_addr(), mark);
  19. if (res_mark == biased_value) {
  20. return BIAS_REVOKED;
  21. }
  22. } else if (mark->has_bias_pattern()) {
  23. Klass* k = obj->klass();
  24. markOop prototype_header = k->prototype_header();
  25. if (!prototype_header->has_bias_pattern()) {
  26. // This object has a stale bias from before the bulk revocation
  27. // for this data type occurred. It's pointless to update the
  28. // heuristics at this point so simply update the header with a
  29. // CAS. If we fail this race, the object's bias has been revoked
  30. // by another thread so we simply return and let the caller deal
  31. // with it.
  32. markOop biased_value = mark;
  33. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(prototype_header, obj->mark_addr(), mark);
  34. assert(!(*(obj->mark_addr()))->has_bias_pattern(), "even if we raced, should still be revoked");
  35. return BIAS_REVOKED;
  36. } else if (prototype_header->bias_epoch() != mark->bias_epoch()) {
  37. // The epoch of this biasing has expired indicating that the
  38. // object is effectively unbiased. Depending on whether we need
  39. // to rebias or revoke the bias of this object we can do it
  40. // efficiently enough with a CAS that we shouldn't update the
  41. // heuristics. This is normally done in the assembly code but we
  42. // can reach this point due to various points in the runtime
  43. // needing to revoke biases.
  44. if (attempt_rebias) {
  45. assert(THREAD->is_Java_thread(), "");
  46. markOop biased_value = mark;
  47. markOop rebiased_prototype = markOopDesc::encode((JavaThread*) THREAD, mark->age(), prototype_header->bias_epoch());
  48. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(rebiased_prototype, obj->mark_addr(), mark);
  49. if (res_mark == biased_value) {
  50. return BIAS_REVOKED_AND_REBIASED;
  51. }
  52. } else {
  53. markOop biased_value = mark;
  54. markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
  55. markOop res_mark = (markOop) Atomic::cmpxchg_ptr(unbiased_prototype, obj->mark_addr(), mark);
  56. if (res_mark == biased_value) {
  57. return BIAS_REVOKED;
  58. }
  59. }
  60. }
  61. }
  62. HeuristicsResult heuristics = update_heuristics(obj(), attempt_rebias);
  63. if (heuristics == HR_NOT_BIASED) {
  64. return NOT_BIASED;
  65. } else if (heuristics == HR_SINGLE_REVOKE) {
  66. Klass *k = obj->klass();
  67. markOop prototype_header = k->prototype_header();
  68. if (mark->biased_locker() == THREAD &&
  69. prototype_header->bias_epoch() == mark->bias_epoch()) {
  70. // A thread is trying to revoke the bias of an object biased
  71. // toward it, again likely due to an identity hash code
  72. // computation. We can again avoid a safepoint in this case
  73. // since we are only going to walk our own stack. There are no
  74. // races with revocations occurring in other threads because we
  75. // reach no safepoints in the revocation path.
  76. // Also check the epoch because even if threads match, another thread
  77. // can come in with a CAS to steal the bias of an object that has a
  78. // stale epoch.
  79. ResourceMark rm;
  80. if (TraceBiasedLocking) {
  81. tty->print_cr("Revoking bias by walking my own stack:");
  82. }
  83. EventBiasedLockSelfRevocation event;
  84. BiasedLocking::Condition cond = revoke_bias(obj(), false, false, (JavaThread*) THREAD, NULL);
  85. ((JavaThread*) THREAD)->set_cached_monitor_info(NULL);
  86. assert(cond == BIAS_REVOKED, "why not?");
  87. if (event.should_commit()) {
  88. event.set_lockClass(k);
  89. event.commit();
  90. }
  91. return cond;
  92. } else {
  93. EventBiasedLockRevocation event;
  94. VM_RevokeBias revoke(&obj, (JavaThread*) THREAD);
  95. VMThread::execute(&revoke);
  96. if (event.should_commit() && (revoke.status_code() != NOT_BIASED)) {
  97. event.set_lockClass(k);
  98. // Subtract 1 to match the id of events committed inside the safepoint
  99. event.set_safepointId(SafepointSynchronize::safepoint_counter() - 1);
  100. event.set_previousOwner(revoke.biased_locker());
  101. event.commit();
  102. }
  103. return revoke.status_code();
  104. }
  105. }
  106. assert((heuristics == HR_BULK_REVOKE) ||
  107. (heuristics == HR_BULK_REBIAS), "?");
  108. EventBiasedLockClassRevocation event;
  109. VM_BulkRevokeBias bulk_revoke(&obj, (JavaThread*) THREAD,
  110. (heuristics == HR_BULK_REBIAS),
  111. attempt_rebias);
  112. VMThread::execute(&bulk_revoke);
  113. if (event.should_commit()) {
  114. event.set_revokedClass(obj->klass());
  115. event.set_disableBiasing((heuristics != HR_BULK_REBIAS));
  116. // Subtract 1 to match the id of events committed inside the safepoint
  117. event.set_safepointId(SafepointSynchronize::safepoint_counter() - 1);
  118. event.commit();
  119. }
  120. return bulk_revoke.status_code();
  121. }

3 偏向锁的撤销

只有当其它线程尝试竞争偏向锁时,持有偏向锁的线程才会释放锁。

偏向锁的撤销由BiasedLocking::revoke_at_safepoint实现:

  1. void BiasedLocking::revoke_at_safepoint(Handle h_obj) {
  2. assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
  3. oop obj = h_obj();
  4. HeuristicsResult heuristics = update_heuristics(obj, false);
  5. if (heuristics == HR_SINGLE_REVOKE) {
  6. revoke_bias(obj, false, false, NULL, NULL);
  7. } else if ((heuristics == HR_BULK_REBIAS) ||
  8. (heuristics == HR_BULK_REVOKE)) {
  9. bulk_revoke_or_rebias_at_safepoint(obj, (heuristics == HR_BULK_REBIAS), false, NULL);
  10. }
  11. clean_up_cached_monitor_info();
  12. }
  1. 偏向锁的撤销动作必须等待全局安全点(safepoint,GC时会让所有线程阻塞的停顿点)
  2. 暂停拥有偏向锁的线程,判断锁对象是否处于被锁定状态
  3. 撤销偏向锁,恢复到无锁(标志位 01)或轻量级锁(标志位 00)状态

偏向锁在Java 1.6后默认启用,但在应用程序启动几s后才激活,可关闭延迟:

  1. -XX:BiasedLockingStartupDelay=0

若确定应用程序中所有锁通常情况下处于竞争状态,可关闭偏向锁:

  1. XX:-UseBiasedLocking=false(默认打开)
偏向锁的释放

遍历线程栈的所有Lock Record,把ObjectReference切断,即ObjectReference = null.

把ObjectReference置null,但锁对象的对象头的Mark Word还是没改变,依然偏向之前的线程,那还是没释放锁的嘛,的确是,线程退出临界区时候,并没有释放偏向锁,这么做是为 : 当再次需要获取锁时,只需要简单判断是否是重入,即可快速获取锁,而不用每次都CAS,这也是偏向锁在只有一个线程访问锁的情景下高效的核心。

总结

  • 当出现锁资源访问的时候,都会在当前线程栈生成一条Lock Record,并且ObjectReference将指向锁对象的对象头 的Mark Word,该设置可能出现多线程,需CAS操作
  • 多线程情况下竞争同一个锁资源,偏向锁的撤销会影响效率
  • 偏向锁的重入计数依靠线程栈里Lock Record个数
  • 偏向锁撤销失败,最终会升级为轻量级锁
  • 偏向锁退出时并没有修改Mark Word,也就是没有释放锁
  • 偏向锁相对轻量级锁来说,当同一线程去再次获取锁的时候,不用进行CAS操作,提高了性能.(轻量级锁在同一线程情况下每次去获取锁,在无锁的状态下,每次都要进行一次CAS操作)
  • 偏向锁只有遇到其他线程尝试竞争偏向锁时,持有偏向锁的线程才会释放锁,线程不会主动去释放偏向锁
  • 偏向锁的撤销是很复杂,成为理解代码的障碍,也阻碍了对同步系统重构,而且现如今基本都是多核系统,偏向锁的劣势越来越明显,所以在Java 15废弃了偏向锁

相关文章