欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-09 21:44:46
警告⚠️:本文耗时很长,先做好心理准备,建议PC端浏览器浏览效果更佳。 本篇我们讲通过大量实例代码及hotspot源码分析偏向锁(批量重偏向、批量撤销)、轻量级锁、重量级锁及锁的膨胀过程(也就是锁的升级过程) 我们先来说一下我们为什么需要锁? 因为在并发情况为了保证线程的安全性,是在一个多线程环境下 ......

警告⚠️:本文耗时很长,先做好心理准备,建议pc端浏览器浏览效果更佳。

本篇我们讲通过大量实例代码及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代码:
public class testdemo {
}
public class demoexample1 {
    static testdemo testdemo;
    public static void main(string[] args) throws exception {
        testdemo= new testdemo();
        synchronized (testdemo){
            system.out.println("lock ing");
            testdemo.hashcode();
            system.out.println(classlayout.parseinstance(testdemo).toprintable());
        }
    }
}
 
运行并分析testdemo.class文件命令:
javap -c demoexample1.class
 
分析结果:
compiled from "demoexample1.java"
public class com.boke.demoexample1 {
  static com.boke.testdemo testdemo;
 
  public com.boke.demoexample1();
    code:
       0: aload_0
       1: invokespecial #1                  // method java/lang/object."<init>":()v
       4: return
 
  public static void main(java.lang.string[]) throws java.lang.exception;
    code:
       0: new           #2                  // class com/boke/testdemo
       3: dup
       4: invokespecial #3                  // method com/boke/testdemo."<init>":()v
       7: putstatic     #4                  // field testdemo:lcom/boke/testdemo;
      10: getstatic     #4                  // field testdemo:lcom/boke/testdemo;
      13: dup
      14: astore_1
      15: monitorenter
      16: getstatic     #5                  // field java/lang/system.out:ljava/io/printstream;
      19: ldc           #6                  // string lock ing
      21: invokevirtual #7                  // method java/io/printstream.println:(ljava/lang/string;)v
      24: getstatic     #4                  // field testdemo:lcom/boke/testdemo;
      27: invokevirtual #8                  // method java/lang/object.hashcode:()i
      30: pop
      31: getstatic     #5                  // field java/lang/system.out:ljava/io/printstream;
      34: getstatic     #4                  // field testdemo:lcom/boke/testdemo;
      37: invokestatic  #9                  // method org/openjdk/jol/info/classlayout.parseinstance:(ljava/lang/object;)lorg/openjdk/jol/info/classlayout;
      40: invokevirtual #10                 // method org/openjdk/jol/info/classlayout.toprintable:()ljava/lang/string;
      43: invokevirtual #7                  // method java/io/printstream.println:(ljava/lang/string;)v
      46: aload_1
      47: monitorexit
      48: goto          56
      51: astore_2
      52: aload_1
      53: monitorexit
      54: aload_2
      55: athrow
      56: return
    exception table:
       from    to  target type
          16    48    51   any
          51    54    51   any
}
通过字节码可以看出包含一个monitorenter指令以及多个monitorexit指令这是因为jvm需要确保所获得的锁在正常执行路径,以及异常执行路径上都能够被解锁。
 
我们可以抽象的理解为每个锁对象拥有一个锁计数器和一个指向持有该锁的线程的指针
  • 当执行 monitorenter 时,如果目标锁对象的计数器为 0,那么说明它没有被其他线程所持有。在这个情况下,java 虚拟机会将该锁对象的持有线程设置为当前线程,并且将其计数器加 1。
  • 在目标锁对象的计数器不为 0 的情况下,如果锁对象的持有线程是当前线程,那么 java 虚拟机可以将其计数器加 1,否则需要等待,直至持有线程释放该锁。当执行 monitorexit 时,java 虚拟机则需将锁对象的计数器减 1。当计数器减为 0 时,那便代表该锁已经被释放掉了。
  • 之所以采用这种计数器的方式,是为了允许同一个线程重复获取同一把锁。举个例子,如果一个 java 类中拥有多个 synchronized 方法,那么这些方法之间的相互调用,不管是直接的还是间接的,都会涉及对同一把锁的重复加锁操作。因此,我们需要设计这么一个可重入的特性,来避免编程里的隐式约束。
  
我们来看一个案例:在不加锁的情况多下通过取两次数值然后进行对比,来模拟两次共享状态的操作:
java代码:
public class demoexample3 {
    public int sharedstate;

    public void nonsafeaction() {
        while (sharedstate < 100000) {
            int former = sharedstate++;
            int latter = sharedstate;
            if (former != latter - 1) {
                system.out.println("observed data race, former is " +
                        former + ", " + "latter is " + latter);
            }
        }
    }
 
    public static void main(string[] args) throws interruptedexception {
        final demoexample3 demoexample3 = new demoexample3();
        thread thread1 = new thread() {
            @override
            public void run() {
                demoexample3.nonsafeaction();
            }
        };
  
        thread thread2 = new thread() {
            @override
            public void run() {
                demoexample3.nonsafeaction();
            }
        };

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }
}
 
没有加 synchronized 关键字的时候打印出来的结果(截取部分):
observed data race, former is 55179, latter is 55181
observed data race, former is 56752, latter is 56754
observed data race, former is 58304, latter is 58306
observed data race, former is 60340, latter is 60342
observed data race, former is 61627, latter is 61629
observed data race, former is 63107, latter is 62946
observed data race, former is 64029, latter is 64029
observed data race, former is 65579, latter is 65581
observed data race, former is 67315, latter is 67317
observed data race, former is 68542, latter is 68542
observed data race, former is 70687, latter is 70687
observed data race, former is 72654, latter is 72656
observed data race, former is 74644, latter is 74646
就会发现,打印出好多与if (former != latter - 1) 条件相符的值,这是错误的,正确的结果应该是一条也没有
 
我们在来看一下加上synchronized关键字的代码:
java代码:
public class demoexample3 {
    public int sharedstate;
  
    public void nonsafeaction() {
        while (sharedstate < 100000) {
            synchronized (this) {
                int former = sharedstate++;
                int latter = sharedstate;
                if (former != latter - 1) {
                    system.out.println("observed data race, former is " +
                            former + ", " + "latter is " + latter);
                }
            }
        }
    }
  
    public static void main(string[] args) throws interruptedexception {
        final demoexample3 demoexample3 = new demoexample3();
        thread thread1 = new thread() {
            @override
            public void run() {
                demoexample3.nonsafeaction();
            }
        };
  
        thread thread2 = new thread() {
            @override
            public void run() {
                demoexample3.nonsafeaction();
            }
        };
thread1.start(); thread2.start(); thread1.join(); thread2.join(); } }

 

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

process finished with exit code 0
 
说明将两次赋值过程用synchronized保护起来,使用this作为互斥单元,就可以避免别的线程并发的去修改 sharedstate;这也就是我刚开说的并发情况下为了保证线程的安全性,我们可以通过加锁来保证。
 
说完我们为什么需要锁,接下来我们介绍偏向锁、轻量级锁、重量级锁及锁的膨胀过程
 
首先我们先从jvm源码中来分析锁的膨胀过程(锁升级的过程)
在jvm中synchronized的是行为是jvm runntime的一部分,所以我们需要先找到 runtime 相关的功能实现。通过在代码中查询类似“monitor_enter”或“monitor enter”,很直观的就可以定位到:
sharedruntime.cpphttp://hg.openjdk.java.net/jdk/jdk/file/6659a8f57d78/src/hotspot/share/runtime/sharedruntime.cpp),它是解释器和编译器运行时的基类:
// handles the uncommon case in locking, i.e., contention or an inflated lock.
jrt_block_entry(void, sharedruntime::complete_monitor_locking_c(oopdesc* _obj, basiclock* lock, javathread* thread))
  // disable objectsynchronizer::quick_enter() in default config
  // on aarch64 and arm until jdk-8153107 is resolved.
  if (arm_only((syncflags & 256) != 0 &&)
      aarch64_only((syncflags & 256) != 0 &&)
      !safepointsynchronize::is_synchronizing()) {
    // only try quick_enter() if we're not trying to reach a safepoint
    // so that the calling thread reaches the safepoint more quickly.
    if (objectsynchronizer::quick_enter(_obj, thread, lock)) return;
  }
  // no_async required because an async exception on the state transition destructor
  // would leave you with the lock held and it would never be released.
  // the normal monitorenter nullpointerexception is thrown without acquiring a lock
  // and the model is that an exception implies the method failed.
  jrt_block_no_async
  oop obj(_obj);
  if (printbiasedlockingstatistics) {
    atomic::inc(biasedlocking::slow_path_entry_count_addr());
  }
  handle h_obj(thread, obj);
  //在 jvm 启动时,我们可以指定是否开启偏向锁
  if (usebiasedlocking) {
  // retry fast entry if bias is revoked to avoid unnecessary inflation
  //fast_enter 是我们熟悉的完整锁获取路径
    objectsynchronizer::fast_enter(h_obj, lock, true, check);
  } else {
  //slow_enter 则是绕过偏向锁,直接进入轻量级锁获取逻辑
    objectsynchronizer::slow_enter(h_obj, lock, check);
  }
  assert(!has_pending_exception, "should have no exception here");
  jrt_block_end
jrt_end
 
synchronizer.cpp),jvm 同步相关的各种基础(不仅仅是 synchronized 的逻辑,包括从本地代码,也就是 jni,触发的 monitor 动作,全都可以在里面找到例如(jni_enter/jni_exit)):
// -----------------------------------------------------------------------------
//  fast monitor enter/exit
// this the fast monitor enter. the interpreter and compiler use
// some assembly copies of this code. make sure update those code
// if the following function is changed. the implementation is
// extremely sensitive to race condition. be careful.
void objectsynchronizer::fast_enter(handle obj, basiclock* lock,
                                    bool attempt_rebias, traps) {
  if (usebiasedlocking) {
    if (!safepointsynchronize::is_at_safepoint()) {
      //biasedlocking定义了偏向锁相关操作,revoke_and_rebias revokeatsafepoint 则定义了当检测到安全点时的处理
      biasedlocking::condition cond = biasedlocking::revoke_and_rebias(obj, attempt_rebias, thread);
      if (cond == biasedlocking::bias_revoked_and_rebiased) {
        return;
      }
    } else {
      assert(!attempt_rebias, "can not rebias toward vm thread");
      biasedlocking::revoke_at_safepoint(obj);
    }
    assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
  }
  //如果获取偏向锁失败,则进入 slow_enter,锁升级
  slow_enter(obj, lock, thread);
}
 
// -----------------------------------------------------------------------------
// interpreter/compiler slow case
// this routine is used to handle interpreter/compiler slow case
// we don't need to use fast path here, because it must have been
// failed in the interpreter/compiler code.
void objectsynchronizer::slow_enter(handle obj, basiclock* lock, traps) {
  markoop mark = obj->mark();
  assert(!mark->has_bias_pattern(), "should not see bias pattern here");
  if (mark->is_neutral()) {
    // anticipate successful cas -- the st of the displaced mark must
    // be visible <= the st performed by the cas.
    // 将目前的 mark word 复制到 displaced header 上
    lock->set_displaced_header(mark);
    // 利用 cas 设置对象的 mark wo
    if (mark == obj()->cas_set_mark((markoop) lock, mark)) {
      return;
    }
    // fall through to inflate() …
    // 检查存在竞争
  } else if (mark->has_locker() &&
             thread->is_lock_owned((address)mark->locker())) {
    assert(lock != mark->locker(), "must not re-lock the same lock");
    assert(lock != (basiclock*)obj->mark(), "don't relock with same basiclock”);
    // 清除
    lock->set_displaced_header(null);
    return;
  }
  // the object header will never be displaced to this lock,
  // so it does not matter what the value is, except that it
  // must be non-zero to avoid looking like a re-entrant lock,
  // and must not look locked either.
  // 重置 displaced header
  lock->set_displaced_header(markoopdesc::unused_mark());
  //锁膨胀
  objectsynchronizer::inflate(thread,
                              obj(),
                              inflate_cause_monitor_enter)->enter(thread);
}
// this routine is used to handle interpreter/compiler slow case
// we don't need to use fast path here, because it must have
// failed in the interpreter/compiler code. simply use the heavy
// weight monitor should be ok, unless someone find otherwise.
void objectsynchronizer::slow_exit(oop object, basiclock* lock, traps) {
  fast_exit(object, lock, thread);
}
 
//锁膨胀
objectmonitor * attr objectsynchronizer::inflate (thread * self, oop object) {
  // inflate mutates the heap ...
  // relaxing assertion for bug 6320749.
  assert (universe::verify_in_progress() ||
          !safepointsynchronize::is_at_safepoint(), "invariant") ;
 
 
  for (;;) {//自旋
      const markoop mark = object->mark() ;
      assert (!mark->has_bias_pattern(), "invariant") ;
 
      // the mark can be in one of the following states:
      // *  inflated     - just return
      // *  stack-locked - coerce it to inflated
      // *  inflating    - busy wait for conversion to complete
      // *  neutral      - aggressively inflate the object.
      // *  biased       - illegal.  we should never see this
  
      // case: inflated已膨胀,即重量级锁
      if (mark->has_monitor()) {//判断当前是否为重量级锁
          objectmonitor * inf = mark->monitor() ;//获取指向objectmonitor的指针
          assert (inf->header()->is_neutral(), "invariant");
          assert (inf->object() == object, "invariant") ;
          assert (objectsynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
          return inf ;
      }
  
      // case: inflation in progress - inflating over a stack-lock.膨胀等待(其他线程正在从轻量级锁转为膨胀锁)
      // some other thread is converting from stack-locked to inflated.
      // only that thread can complete inflation -- other threads must wait.
      // the inflating value is transient.
      // currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
      // we could always eliminate polling by parking the thread on some auxiliary list.
      if (mark == markoopdesc::inflating()) {
         tevent (inflate: spin while inflating) ;
         readstablemark(object) ;
         continue ;
      }
  
      // case: stack-locked栈锁(轻量级锁)
      // could be stack-locked either by this thread or by some other thread.
      //
      // note that we allocate the objectmonitor speculatively, _before_ attempting
      // to install inflating into the mark word.  we originally installed inflating,
      // allocated the objectmonitor, and then finally sted the address of the
      // objectmonitor into the mark.  this was correct, but artificially lengthened
      // the interval in which inflated appeared in the mark, thus increasing
      // the odds of inflation contention.
      //
      // we now use per-thread private objectmonitor free lists.
      // these list are reprovisioned from the global free list outside the
      // critical inflating...st interval.  a thread can transfer
      // multiple objectmonitors en-mass from the global free list to its local free list.
      // this reduces coherency traffic and lock contention on the global free list.
      // using such local free lists, it doesn't matter if the omalloc() call appears
      // before or after the cas(inflating) operation.
      // see the comments in omalloc().
 
      if (mark->has_locker()) {
          objectmonitor * m = omalloc (self) ;//获取一个可用的objectmonitor
          // optimistically prepare the objectmonitor - anticipate successful cas
          // we do this before the cas in order to minimize the length of time
          // in which inflating appears in the mark.
          m->recycle();
          m->_responsible  = null ;
          m->owneristhread = 0 ;
          m->_recursions   = 0 ;
          m->_spinduration = objectmonitor::knob_spinlimit ;   // consider: maintain by type/class
  
          markoop cmp = (markoop) atomic::cmpxchg_ptr (markoopdesc::inflating(), object->mark_addr(), mark) ;
          if (cmp != mark) {//cas失败//cas失败,说明冲突了,自旋等待//cas失败,说明冲突了,自旋等待//cas失败,说明冲突了,自旋等待
             omrelease (self, m, true) ;//释放监视器锁
             continue ;       // interference -- just retry
          } 
 
          // we've successfully installed inflating (0) into the mark-word.
          // this is the only case where 0 will appear in a mark-work.
          // only the singular thread that successfully swings the mark-word
          // to 0 can perform (or more precisely, complete) inflation.
          //
          // why do we cas a 0 into the mark-word instead of just casing the
          // mark-word from the stack-locked value directly to the new inflated state?
          // consider what happens when a thread unlocks a stack-locked object.
          // it attempts to use cas to swing the displaced header value from the
          // on-stack basiclock back into the object header.  recall also that the
          // header value (hashcode, etc) can reside in (a) the object header, or
          // (b) a displaced header associated with the stack-lock, or (c) a displaced
          // header in an objectmonitor.  the inflate() routine must copy the header
          // value from the basiclock on the owner's stack to the objectmonitor, all
          // the while preserving the hashcode stability invariants.  if the owner
          // decides to release the lock while the value is 0, the unlock will fail
          // and control will eventually pass from slow_exit() to inflate.  the owner
          // will then spin, waiting for the 0 value to disappear.   put another way,
          // the 0 causes the owner to stall if the owner happens to try to
          // drop the lock (restoring the header from the basiclock to the object)
          // while inflation is in-progress.  this protocol avoids races that might
          // would otherwise permit hashcode values to change or "flicker" for an object.
          // critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
          // 0 serves as a "busy" inflate-in-progress indicator
          // fetch the displaced mark from the owner's stack.
          // the owner can't die or unwind past the lock while our inflating
          // object is in the mark.  furthermore the owner can't complete
          // an unlock on the object, either.
          markoop dmw = mark->displaced_mark_helper() ;
          assert (dmw->is_neutral(), "invariant") ;
          //cas成功,设置objectmonitor的_header、_owner和_object等
          // setup monitor fields to proper values -- prepare the monitor
          m->set_header(dmw) ;

          // optimization: if the mark->locker stack address is associated
          // with this thread we could simply set m->_owner = self and
          // m->owneristhread = 1. note that a thread can inflate an object
          // that it has stack-locked -- as might happen in wait() -- directly
          // with cas.  that is, we can avoid the xchg-null .... st idiom.
          m->set_owner(mark->locker());
          m->set_object(object);
          // todo-fixme: assert basiclock->dhw != 0.
 
          // must preserve store ordering. the monitor state must
          // be stable at the time of publishing the monitor address.
          guarantee (object->mark() == markoopdesc::inflating(), "invariant") ;
          object->release_set_mark(markoopdesc::encode(m));
  
          // hopefully the performance counters are allocated on distinct cache lines
          // to avoid false sharing on mp systems ...
          if (objectmonitor::_sync_inflations != null) objectmonitor::_sync_inflations->inc() ;
          tevent(inflate: overwrite stacklock) ;
          if (tracemonitorinflation) {
            if (object->is_instance()) {
              resourcemark rm;
              tty->print_cr("inflating object " intptr_format " , mark " intptr_format " , type %s",
                (void *) object, (intptr_t) object->mark(),
                object->klass()->external_name());
            }
          }
          return m ;
      }
  
      // case: neutral 无锁
      // todo-fixme: for entry we currently inflate and then try to cas _owner.
      // if we know we're inflating for entry it's better to inflate by swinging a
      // pre-locked objectmonitor pointer into the object header.   a successful
      // cas inflates the object *and* confers ownership to the inflating thread.
      // in the current implementation we use a 2-step mechanism where we cas()
      // to inflate and then cas() again to try to swing _owner from null to self.
      // an inflatetry() method that we could call from fast_enter() and slow_enter()
      // would be useful.
 
      assert (mark->is_neutral(), "invariant");
      objectmonitor * m = omalloc (self) ;
      // prepare m for installation - set monitor to initial state
      m->recycle();
      m->set_header(mark);
      m->set_owner(null);
      m->set_object(object);
      m->owneristhread = 1 ;
      m->_recursions   = 0 ;
      m->_responsible  = null ;
      m->_spinduration = objectmonitor::knob_spinlimit ;       // consider: keep metastats by type/class
  
      if (atomic::cmpxchg_ptr (markoopdesc::encode(m), object->mark_addr(), mark) != mark) {
          m->set_object (null) ;
          m->set_owner  (null) ;
          m->owneristhread = 0 ;
          m->recycle() ;
          omrelease (self, m, true) ;
          m = null ;
          continue ;
          // interference - the markword changed - just retry.
          // the state-transitions are one-way, so there's no chance of
          // live-lock -- "inflated" is an absorbing state.
      }
  
      // hopefully the performance counters are allocated on distinct
      // cache lines to avoid false sharing on mp systems ...
      if (objectmonitor::_sync_inflations != null) objectmonitor::_sync_inflations->inc() ;
      tevent(inflate: overwrite neutral) ;
      if (tracemonitorinflation) {
        if (object->is_instance()) {
          resourcemark rm;
          tty->print_cr("inflating object " intptr_format " , mark " intptr_format " , type %s",
            (void *) object, (intptr_t) object->mark(),
            object->klass()->external_name());
        }
      }
      return m ;
  }
}

  

膨胀过程的实现比较复杂,大概实现过程如下:

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的情况下:
//创建一个啥都没有的类: 
public class testdemo {}
 
public class demoexample {
    static testdemo testdemo;
    public static void main(string[] args) throws exception {
        //此处睡眠50000ms,取消jvm默认偏向锁延迟4000ms
        thread.sleep(5000);
        testdemo= new testdemo();
 
        //hash计算?
        //testdemo.hashcode();
 
        system.out.println("befor lock");
        //无锁:偏向锁?
        system.out.println(classlayout.parseinstance(testdemo).toprintable());
 
        synchronized (testdemo){
            system.out.println("lock ing");
            system.out.println(classlayout.parseinstance(testdemo).toprintable());
        }
 
        system.out.println("after lock");
        system.out.println(classlayout.parseinstance(testdemo).toprintable());
    }
}
 
运行结果:
befor lock
offset  size   type description                               value
      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
lock ing
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 80 80 ac (00000101 10000000 10000000 10101100) (-1400864763)
      4     4        (object header)                           8d 7f 00 00 (10001101 01111111 00000000 00000000) (32653)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
after lock
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 80 80 ac (00000101 10000000 10000000 10101100) (-1400864763)
      4     4        (object header)                           8d 7f 00 00 (10001101 01111111 00000000 00000000) (32653)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
分析结果:
befor lock:绿颜色表示:虽然是偏向锁,但是黄颜色表示没有任何线程持有锁(一个对象被初始化的时候是可偏向的
lock  ing: 绿颜色表示偏向锁,黄颜色的表示当前线程拿到锁
after lock:绿颜色表示偏向锁,黄颜色的表示当前线程拿到锁,还是偏向的状态;(偏向锁退出锁后依然是偏向状态
 
jvm在初始化一个对象的时候,如果没有启用偏向锁延迟,就会去判断这个对象是否可以被偏向,如果可以就是偏向锁;退出同步代码块 还是偏向锁。
 
二、在对象进行hashcode计算之后就会输出下面的结果(也就是代码的这块testdemo.hashcode()去掉注释,进行hashcode运算):
befor lock
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
lock ing
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           f8 28 4b 0c (11111000 00101000 01001011 00001100) (206252280)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
after lock
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 80 80 ac (00000101 10000000 10000000 10101100) (-1400864763)
      4     4        (object header)                           8d 7f 00 00 (10001101 01111111 00000000 00000000) (32653)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
结果显示并不是偏向锁了,说明对象在计算过hashcode之后就不能被偏向
  1. 具体来说,在线程进行加锁时,如果该锁对象支持偏向锁,那么 java 虚拟机会通过 cas操作,将当前线程的地址记录在锁对象的标记字段之中,并且将标记字段的最后三位设置为:1 01;
  2. 在接下来的运行过程中,每当有线程请求这把锁,java 虚拟机只需判断锁对象标记字段中:最后三位是否为: 1 01,是否包含当前线程的地址,以及 epoch 值是否和锁对象的类的epoch 值相同。如果都满足,那么当前线程持有该偏向锁,可以直接返回;
 
这里的 epoch 值是一个什么概念呢?
  • 我们先从偏向锁的撤销讲起。当请求加锁的线程和锁对象标记字段保持的线程地址不匹配时(而且 epoch 值相等,如若不等,那么当前线程可以将该锁重偏向至自己),java 虚拟机需要撤销该偏向锁。这个撤销过程非常麻烦,它要求持有偏向锁的线程到达安全点,再将偏向锁替换成轻量级锁;
  • 如果某一类锁对象的总撤销数超过了一个阈值(对应 jvm参数 -xx:biasedlockingbulkrebiasthreshold,默认为 20),那么 java 虚拟机会宣布这个类的偏向锁失效;(这里说的就是批量重偏向
       jvm源码:
product(intx, biasedlockingbulkrebiasthreshold, 20,                       \
        "threshold of number of revocations per type to try to "          \
        "rebias all objects in the heap of that type")                    \
        range(0, max_intx)                                                \
        constraint(biasedlockingbulkrebiasthresholdfunc,afterergo)        \

 

  • 具体的做法便是在每个类中维护一个 epoch 值,你可以理解为第几代偏向锁。当设置偏向锁时,java 虚拟机需要将该 epoch 值复制到锁对象的标记字段中;
  • 在宣布某个类的偏向锁失效时,java 虚拟机实则将该类的 epoch 值加 1,表示之前那一代的偏向锁已经失效。而新设置的偏向锁则需要复制新的 epoch 值;
  • 为了保证当前持有偏向锁并且已加锁的线程不至于因此丢锁,java 虚拟机需要遍历所有线程的 java 栈,找出该类已加锁的实例,并且将它们标记字段中的 epoch 值加 1。该操作需要所有线程处于安全点状态;
  • 如果总撤销数超过另一个阈值(对应 jvm 参数 -xx:biasedlockingbulkrevokethreshold,默认值为 40),那么 java 虚拟机会认为这个类已经不再适合偏向锁。此时,java 虚拟机会撤销该类实例的偏向锁,并且在之后的加锁过程中直接为该类实例设置轻量级锁(这里说的就是偏向批量撤销)
      
jvm源码:
product(intx, biasedlockingbulkrevokethreshold, 40,                       \
        "threshold of number of revocations per type to permanently "     \
        "revoke biases of all objects in the heap of that type")          \
        range(0, max_intx)                                                \
        constraint(biasedlockingbulkrevokethresholdfunc,afterergo)   

  


 

接下来我们分析两个批量重偏向相关案例(禁止偏向锁延迟的情况下:-xx:+usebiasedlocking ):
 
案例一:
java代码:
public class testdemo {
}
public class demoexample4 {
    public static void main(string[] args) throws interruptedexception {
        test1();
    }
  
   public class demoexample5 {
    public static void main(string[] args) throws interruptedexception {
        test1();
    }
  
    /**
     * 仅证明批量重偏向
     * @throws interruptedexception
     */
    public  static  void test1() throws interruptedexception {
        list<testdemo> list = new arraylist<>();
        for (int i = 0; i < 100; i++) {
            list.add(new testdemo());
        }
        thread t1 = new thread(()->{
            system.out.println("加锁前 get(0) 应该是无锁可偏向 "+ classlayout.parseinstance(list.get(0)).toprintable());
            for (testdemo a:list  ) {
                synchronized (a){
                    system.out.print("加锁 >");
                }
            }
            system.out.println();
            system.out.println("加锁后 get(0) 应该是偏向锁"+classlayout.parseinstance(list.get(0)).toprintable());
            try {
                timeunit.seconds.sleep(1000);//这里不让线程死,防止线程id复用
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        });
        t1.start();
        timeunit.seconds.sleep(5);
        thread t2 = new thread(()->{
            for (int i = 0; i < 40; i++) {
                testdemo a = list.get(i);
                synchronized (a){
                    system.out.print("加锁 >");
                }
                if (i==18){
                    system.out.println();
                    system.out.println("加锁后 get(18) 应该是无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(i)).toprintable());
                }
                if (i==19){ //开始重偏向
                    system.out.println();
                    system.out.println("加锁后 get(19) 应该是偏向锁 "+classlayout.parseinstance(list.get(i)).toprintable());
                    system.out.println("加锁后 get(0) 应该是无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(0)).toprintable());
                    system.out.println("加锁后 get(99) 应该是偏向锁 偏向t1 "+classlayout.parseinstance(list.get(99)).toprintable());
                }
                if (i==20){
                    system.out.println();
                    system.out.println("加锁后 get(20) 应该是偏向锁 "+classlayout.parseinstance(list.get(i)).toprintable());
                }
            }
        });
        t2.start();
    }
}
 
运行并分析结果:
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
 
加锁后 get(0) 应该是偏向锁com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 30 8a 73 (00000101 00110000 10001010 01110011) (1938436101)
      4     4        (object header)                           c4 7f 00 00 (11000100 01111111 00000000 00000000) (32708)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
加锁后 get(18) 应该是无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁 >
加锁后 get(19) 应该是偏向锁 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 41 0b 75 (00000101 01000001 00001011 01110101) (1963671813)
      4     4        (object header)                           c4 7f 00 00 (11000100 01111111 00000000 00000000) (32708)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁后 get(0) 应该是无锁(轻量级锁释放 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁后 get(99) 应该是偏向锁 偏向t1 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 30 8a 73 (00000101 00110000 10001010 01110011) (1938436101)
      4     4        (object header)                           c4 7f 00 00 (11000100 01111111 00000000 00000000) (32708)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁 >
加锁后 get(20) 应该是偏向锁 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 41 0b 75 (00000101 01000001 00001011 01110101) (1963671813)
      4     4        (object header)                           c4 7f 00 00 (11000100 01111111 00000000 00000000) (32708)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
 
案例二:
java代码:
public class testdemo {
}
public class demoexample7 {
    public static void main(string[] args) throws exception {
 
        list<testdemo> list = new arraylist<>();
        //初始化数据
        for (int i = 0; i < 100; i++) {
            list.add(new testdemo());
        }
  
        thread t1 = new thread() {
            string name = "1";
            public void run() {
                system.out.printf(name);
                for (testdemo a : list) {
                    synchronized (a) {
                        if (a == list.get(10)) {
                            system.out.println("t1 预期是偏向锁" + 10 + classlayout.parseinstance(a).toprintable());
                        }
                    }
                }
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        };
        t1.start();
        thread.sleep(5000);
        system.out.println("main 预期是偏向锁" + 10 + classlayout.parseinstance(list.get(10)).toprintable());
  
        thread t2 = new thread() {
            string name = "2";
 
            public void run() {
                system.out.printf(name); 
                for (int i = 0; i < 100; i++) {
                    testdemo a = list.get(i);
                    // hack 为了在批量重偏向发生后再次加锁,前面使用了轻量级锁的对象
                    if (i == 20) {
                        a = list.get(9);
                    }
  
                    synchronized (a) {
                        if (i == 10) {
                            //已经经过偏向锁撤销,并使用轻量级锁的对象,释放后  状态依为001 无锁状态
                            system.out.println("t2 i=10 get(1)预期是无锁" + classlayout.parseinstance(list.get(1)).toprintable());
                            //因为和t1交替使用对象a 没有发生竞争,但偏向锁已偏向,另外不满足重偏向条件,所以使用轻量级锁
                            system.out.println("t2 i=10 get(i) 预期轻量级锁 " + i + classlayout.parseinstance(a).toprintable());
                        }
                        if (i == 19) {
                            //已经经过偏向锁撤销,并使用轻量级锁的对象,在批量重偏向发生后。不会影响现有的状态  状态依然为001
                            system.out.println("t2  i=19  get(10)预期是无锁" + 10 + classlayout.parseinstance(list.get(10)).toprintable());
                            //满足重偏向条件后,已偏向的对象可以重新使用偏向锁 将线程id指向当前线程,101
                            system.out.println("t2  i=19  get(i) 满足重偏向条件20 预期偏向锁 " + i + classlayout.parseinstance(a).toprintable());
                            //满足重偏向条件后,已偏向还为需要加锁的对象依然偏向线程1 因为偏向锁的撤销是发生在下次加锁的时候。这里没有执行到同步此对象,所以依然偏向t1
                            system.out.println("t2  i=19  get(i) 满足重偏向条件20 但后面的对象没有被加锁,所以依旧偏向t1 " + i + classlayout.parseinstance(list.get(40)).toprintable());
                        }
                        if (i == 20) {
                            //满足重偏向条件后,再次加锁之前使用了轻量级锁的对象,依然轻量级锁,证明重偏向这个状态只针对偏向锁。已经发生锁升级的,不会退回到偏向锁
                            system.out.println("t2  i=20 满足偏向条件之后,之前被设置为无锁状态的对象,不可偏向,这里使用的是轻量级锁  get(9)预期是轻量级锁 " + classlayout.parseinstance(a).toprintable());
                        }
                    }
                }
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        };
        t2.start();
        thread.sleep(5000);
    }
}
 
运行并分析结果:
t1 预期是偏向锁10  com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 78 86 af (00000101 01111000 10000110 10101111) (-1350141947)
      4     4        (object header)                           f6 7f 00 00 (11110110 01111111 00000000 00000000) (32758)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
main 预期是偏向锁 10 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 78 86 af (00000101 01111000 10000110 10101111) (-1350141947)
      4     4        (object header)                           f6 7f 00 00 (11110110 01111111 00000000 00000000) (32758)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
2t2 i=10 get(1)预期是无锁 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2 i=10 get(i) 预期轻量级锁 10 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 69 42 08 (00001000 01101001 01000010 00001000) (138569992)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2  i=19  get(10)预期是无锁10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2  i=19  get(i) 满足重偏向条件20 预期偏向锁 19com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 71 95 ae (00000101 01110001 10010101 10101110) (-1365937915)
      4     4        (object header)                           f6 7f 00 00 (11110110 01111111 00000000 00000000) (32758)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2  i=19  get(i) 满足重偏向条件20 但后面的对象没有被加锁,所以依旧偏向t1 19com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 78 86 af (00000101 01111000 10000110 10101111) (-1350141947)
      4     4        (object header)                           f6 7f 00 00 (11110110 01111111 00000000 00000000) (32758)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2  i=20 满足偏向条件之后,之前被设置为无锁状态的对象,不可偏向,这里使用的是轻量级锁  get(9)预期是轻量级锁 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 69 42 08 (00001000 01101001 01000010 00001000) (138569992)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           05 d6 00 f8 (00000101 11010110 00000000 11111000) (-134162939)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
接下来我们分析两个批量偏向撤销相关案例(禁止偏向锁延迟的情况下:-xx:+usebiasedlocking ):
案例一:
public class testdemo {
}
 
public class demoexample6 {
    public static void main(string[] args) throws interruptedexception {
        test2();
    }
  
    /**
     * 证明偏量偏向撤销
     * @throws interruptedexception
     */
    public  static  void test2() throws interruptedexception {
        list<testdemo> list = new arraylist<testdemo>();
        for (int i = 0; i < 100; i++) {
            list.add(new testdemo());
        }
        thread t1 = new thread(()->{
            system.out.println("加锁前 get(0) 应该是无锁可偏向 "+classlayout.parseinstance(list.get(0)).toprintable());
            for (testdemo a:list  ) {
                synchronized (a){
                    system.out.print("加锁 >");
                }
            }
            system.out.println();
            system.out.println("加锁后 get(0) 应该是偏向锁"+classlayout.parseinstance(list.get(0)).toprintable());
            try {
                timeunit.seconds.sleep(1000);//这里不让线程死,防止线程id复用
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        });
        t1.start();
        timeunit.seconds.sleep(5);
        thread t2 = new thread(()->{
            for (int i = 0; i < 100; i++) {
                testdemo a = list.get(i);
                synchronized (a){
                    system.out.println(thread.currentthread().getid()+"加锁 >");
                }
                try {
                    timeunit.milliseconds.sleep(100);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
                if (i==9){//这里刚好是第19个上锁的(同样是第19个偏向锁升级的)
                    system.out.println();
                    system.out.println("加锁后 get(9) 应该是无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(i)).toprintable());
                }
                if (i==10){//这里刚好是第21个上锁的
                    system.out.println();
                    system.out.println("加锁后 get(10) 应该是偏向锁 偏向t2 "+classlayout.parseinstance(list.get(i)).toprintable());
                }
                if (i==50){//50开始升级为轻量级锁(同样是第21个偏向锁升级的)
                    system.out.println();
                    system.out.println("加锁后 get(50) 无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(i)).toprintable());
                }
                if (i==59){//60(同样是第39个偏向锁升级的)
                    system.out.println();
                    system.out.println("加锁后 get(59) 无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(i)).toprintable());
                }
                if (i==69){//69(同样是第59个偏向锁升级的)
                    system.out.println();
                    system.out.println("加锁后 get(69) 无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(i)).toprintable());
                    testdemo a1 = new testdemo();
                    synchronized (a1){
                        system.out.println("偏向撤销发生后的该类新建的对象都不会再偏向任何线程 "+classlayout.parseinstance(a1).toprintable());
                    }
                }
            }
        });
  
        thread t3 = new thread(()->{
            for (int i = 99; i >= 0; i--) {
                testdemo a = list.get(i);
                synchronized (a){
                    system.out.println(thread.currentthread().getid()+"加锁 >");
                }
                try {
                    timeunit.milliseconds.sleep(100);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
                /**
                 * 重点:重偏向撤销
                 */
                if (i==40){//40升级为轻量级锁(同样是第40个偏向锁升级的,这时候发生偏向撤销)
                    system.out.println();
                    system.out.println("加锁后 get("+i+") 应该是无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(0)).toprintable());
                    testdemo a1 = new testdemo();
                    synchronized (a1){
                        system.out.println("偏向撤销发生后的该类新建的对象都不会再偏向任何线程 "+classlayout.parseinstance(a1).toprintable());
                    }
                }
                if (i==30){//39升级为轻量级锁(同样是第42个偏向锁升级的)
                    system.out.println();
                    system.out.println("加锁后 get("+i+") 应该是无锁(轻量级锁释放) "+classlayout.parseinstance(list.get(0)).toprintable());
                    testdemo a1 = new testdemo();
                    synchronized (a1){
                        system.out.println("偏向撤销发生后的该类新建的对象都不会再偏向任何线程 "+classlayout.parseinstance(a1).toprintable());
                    }
                }
            }
        });
        t2.start();
        timeunit.milliseconds.sleep(50);
        t3.start();
    }
}  
 
运行结果(截取部分):
加锁前 get(0) 应该是无锁可偏向 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >加锁 >
 
加锁后 get(0) 应该是偏向锁com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 e0 84 08 (00000101 11100000 10000100 00001000) (142925829)
      4     4        (object header)                           b1 7f 00 00 (10110001 01111111 00000000 00000000) (32689)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
加锁后 get(9) 应该是无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
15加锁 >
 
 
加锁后 get(90) 应该是偏向锁 偏向t3com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 89 01 0c (00000101 10001001 00000001 00001100) (201427205)
      4     4        (object header)                           b1 7f 00 00 (10110001 01111111 00000000 00000000) (32689)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
加锁后 get(10) 应该是偏向锁 偏向t2 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 b1 0a 08 (00000101 10110001 00001010 00001000) (134918405)
      4     4        (object header)                           b1 7f 00 00 (10110001 01111111 00000000 00000000) (32689)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
15加锁 >
 
 
加锁后 get(89) 应该是无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
加锁后 get(50) 无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
15加锁 >
  
加锁后 get(49) 应该是无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
加锁后 get(59) 无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  
15加锁 > 
 
加锁后 get(40) 应该是无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  
偏向撤销发生后的该类新建的对象都不会再偏向任何线程 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           48 18 a6 09 (01001000 00011000 10100110 00001001) (161880136)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
加锁后 get(69) 无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  
偏向撤销发生后的该类新建的对象都不会再偏向任何线程 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           50 e8 95 09 (01010000 11101000 10010101 00001001) (160819280)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  
15加锁 >
 
加锁后 get(30) 应该是无锁(轻量级锁释放) com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  
偏向撤销发生后的该类新建的对象都不会再偏向任何线程 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           48 18 a6 09 (01001000 00011000 10100110 00001001) (161880136)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
案例二:
public class testdemo {
} 
public class demoexample8 {
    public static void main(string[] args) throws exception {
        list<testdemo> list = new arraylist<>();
        list<testdemo> list2 = new arraylist<>();
        list<testdemo> list3 = new arraylist<>();
        for (int i = 0; i < 100; i++) {
            list.add(new testdemo());
            list2.add(new testdemo());
            list3.add(new testdemo());
        }
        //偏向锁
        system.out.println("初始状态" + 10 + classlayout.parseclass(testdemo.class).toprintable());
  
        thread t1 = new thread() {
            string name = "1"; 
            public void run() {
                system.out.printf(name);
                for (testdemo a : list) {
                    synchronized (a) {
                        if (a == list.get(10)) {
                            //偏向锁
                            system.out.println("t1 预期是偏向锁" + 10 + classlayout.parseinstance(a).toprintable());
                        }
                    }
                }
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                } 
            }
        };
        t1.start();
        thread.sleep(5000);
        //偏向锁
        system.out.println("main 预期是偏向锁" + 10 + classlayout.parseinstance(list.get(10)).toprintable()); 
        thread t2 = new thread() {
            string name = "2"; 
            public void run() {
                system.out.printf(name); 
                for (int i = 0; i < 100; i++) {
                    testdemo a = list.get(i);
                    synchronized (a) {
                        if (a == list.get(10)) {
                            system.out.println("t2 i=10 get(1)预期是无锁" + classlayout.parseinstance(list.get(1)).toprintable());//偏向锁
                            system.out.println("t2 i=10 get(10) 预期轻量级锁 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                        if (a == list.get(19)) {
                            system.out.println("t2  i=19  get(10)预期是无锁" + 10 + classlayout.parseinstance(list.get(10)).toprintable());//偏向锁
                            system.out.println("t2  i=19  get(19) 满足重偏向条件20 预期偏向锁 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                            system.out.println("类的对象累计撤销达到20");
                        }  
                    }
                } 
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                } 
            }
        };
        t2.start(); 
        thread.sleep(5000);
 
        thread t3 = new thread() {
            string name = "3";
            public void run() { 
                system.out.printf(name);
                for (testdemo a : list2) {
                    synchronized (a) {
                        if (a == list2.get(10)) {
                            system.out.println("t3 预期是偏向锁" + 10 + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                    }
                }
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        };
        t3.start();
        thread.sleep(5000);
 
        thread t4 = new thread() {
            string name = "4"; 
            public void run() {
                system.out.printf(name);
                for (int i = 0; i < 100; i++) {
                    testdemo a = list2.get(i);
                    synchronized (a) {
                        if (a == list2.get(10)) {
                            system.out.println("t4 i=10 get(1)预期是无锁" + classlayout.parseinstance(list2.get(1)).toprintable());//偏向锁
                            system.out.println("t4 i=10 get(10) 当前不满足重偏向条件 20 预期轻量级锁 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                        if (a == list2.get(19)) {
                            system.out.println("t4  i=19  get(10)预期是无锁" + 10 + classlayout.parseinstance(list2.get(10)).toprintable());//偏向锁
                            system.out.println("t4 i=19 get(19) 当前满足重偏向条件 20 但a类的对象累计撤销达到40 预期轻量级锁 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                            system.out.println("类的对象累计撤销达到40");
                        }
                        if (a == list2.get(20)) {
                            system.out.println("t4 i=20 get(20) 当前满足重偏向条件 20 预期轻量级锁 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                    }
                }
            }
        };
        t4.start();
        thread.sleep(5000);
        system.out.println("main 预期是偏向锁" + 10 + classlayout.parseinstance(list3.get(0)).toprintable());//偏向锁
        thread t5 = new thread() {
            string name = "5";
            public void run() {
                system.out.printf(name);
                for (testdemo a : list3) {
                    synchronized (a) {
                        if (a == list3.get(10)) {
                            system.out.println("t5 预期是轻量级锁,类的对象累计撤销达到40 不可以用偏向锁了" + 10 + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                    }
                }
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        };
        t5.start();
        thread.sleep(5000);
        system.out.println("main 预期是偏向锁" + 10 + classlayout.parseinstance(list.get(10)).toprintable());//偏向锁
 
        thread t6 = new thread() {
            string name = "6";
            public void run() {
                system.out.printf(name);
                for (int i = 0; i < 100; i++) {
                    testdemo a = list3.get(i);
                    synchronized (a) {
                        if (a == list3.get(10)) {
                            system.out.println("t6 i=10 get(1)预期是无锁" + classlayout.parseinstance(list3.get(1)).toprintable());//偏向锁
                            system.out.println("t6 i=10 get(10) 预期轻量级锁 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                        if (a == list3.get(19)) {
                            system.out.println("t6  i=19  get(10)预期是无锁" + 10 + classlayout.parseinstance(list3.get(10)).toprintable());//偏向锁
                            system.out.println("t6  i=19  get(19) 满足重偏向条件20 但类的对象累计撤销达到40 不可以用偏向锁了 " + i + classlayout.parseinstance(a).toprintable());//偏向锁
                        }
                    }
                }
 
                try {
                    thread.sleep(100000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        };
        t6.start();
        thread.sleep(5000);
 
        system.out.println("由于撤销锁次数达到默认的 biasedlockingbulkrevokethreshold=40 这里实例化的对象 是无锁状态" + classlayout.parseinstance(new testdemo()).toprintable());//偏向锁
     system.out.println("撤销偏向后状态" + 10 + classlayout.parseinstance(new testdemo()).toprintable());//偏向锁
  } 
}

   

运行结果:
初始状态10 com.boke.testdemo object internals:
offset  size   type description                               value
      0    12        (object header)                           n/a
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
1t1 预期是偏向锁10 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 e0 86 8e (00000101 11100000 10000110 10001110) (-1903763451)
      4     4        (object header)                           ec 7f 00 00 (11101100 01111111 00000000 00000000) (32748)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
main 预期是偏向锁10 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 e0 86 8e (00000101 11100000 10000110 10001110) (-1903763451)
      4     4        (object header)                           ec 7f 00 00 (11101100 01111111 00000000 00000000) (32748)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
2t2 i=10 get(1)预期是无锁com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2 i=10 get(10) 预期轻量级锁 10 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 99 7a 03 (00001000 10011001 01111010 00000011) (58366216)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2  i=19  get(10)预期是无锁10 com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t2  i=19  get(19) 满足重偏向条件20 预期偏向锁 19com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 09 90 91 (00000101 00001001 10010000 10010001) (-1852831483)
      4     4        (object header)                           ec 7f 00 00 (11101100 01111111 00000000 00000000) (32748)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
类的对象累计撤销达到20
3t3 预期是偏向锁10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 09 89 90 (00000101 00001001 10001001 10010000) (-1870067451)
      4     4        (object header)                           ec 7f 00 00 (11101100 01111111 00000000 00000000) (32748)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
4t4 i=10 get(1)预期是无锁com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t4 i=10 get(10) 当前不满足重偏向条件 20 预期轻量级锁 10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 f9 9a 03 (00001000 11111001 10011010 00000011) (60487944)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t4  i=19  get(10)预期是无锁10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t4 i=19 get(19) 当前满足重偏向条件 20 但a类的对象累计撤销达到40 预期轻量级锁 19com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 f9 9a 03 (00001000 11111001 10011010 00000011) (60487944)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
类的对象累计撤销达到40
t4 i=20 get(20) 当前满足重偏向条件 20 预期轻量级锁 20com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 f9 9a 03 (00001000 11111001 10011010 00000011) (60487944)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
main 预期是偏向锁10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
5t5 预期是轻量级锁,a类的对象累计撤销达到40 不可以用偏向锁了10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 f9 9a 03 (00001000 11111001 10011010 00000011) (60487944)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
main 预期是偏向锁10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
6t6 i=10 get(1)预期是无锁com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t6 i=10 get(10) 预期轻量级锁 10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 29 ab 03 (00001000 00101001 10101011 00000011) (61548808)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t6  i=19  get(10)预期是无锁10com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t6  i=19  get(19) 满足重偏向条件20 但a类的对象累计撤销达到40 不可以用偏向锁了 19com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           08 29 ab 03 (00001000 00101001 10101011 00000011) (61548808)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
由于类撤销锁次数达到默认的 biasedlockingbulkrevokethreshold=40 这里实例化的对象 是无锁状态com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 

撤销偏向后状态10com.boke.testdemo object internals:
offset size type description                     value
  0    4        (object header)                01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  4    4        (object header)               00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  8    4        (object header)                bf c3 00 f8 (10111111 11000011 00000000 11111000) (-134167617)
  12   4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 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互斥量产生的性能损耗
  • 在竞争激烈时,轻量级锁会多做很多额外操作,导致性能下降
  • 可以认为两个线程交替执行的情况下请求同一把锁

 

分析一个由偏向锁膨胀成轻量级锁的案例:
public class testdemo {
}
public class demoexample9 {
    public static void main(string[] args) throws exception {
        testdemo testdemo = new testdemo();
 
        //子线程
        thread t1 = new thread(){
            @override
            public void run() {
                synchronized (testdemo){
                    system.out.println("t1 lock ing");
                    system.out.println(classlayout.parseinstance(testdemo).toprintable());
                }
            }
        };
        
        t1.join();
 
        //主线程
        synchronized (testdemo){
            system.out.println("main lock ing");
            system.out.println(classlayout.parseinstance(testdemo).toprintable());
        }
 
    }
}

  

运行结果(两个线程交替执行的情况下):
main lock ing
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           e8 48 95 09 (11101000 01001000 10010101 00001001) (160778472)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           a0 c1 00 f8 (10100000 11000001 00000000 11111000) (-134168160)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 

 
重量级锁:

 

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

  

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

public class testdemo {
}
public class demoexample9 {
    public static void main(string[] args) throws exception {
        testdemo testdemo = new testdemo();
 
 
        thread t1 = new thread(){
            @override
            public void run() {
                synchronized (testdemo){
                    system.out.println("t1 lock ing");
                    system.out.println(classlayout.parseinstance(testdemo).toprintable());
                }
            }
        };
 
        t1.start();
 
        synchronized (testdemo){
            system.out.println("main lock ing");
            system.out.println(classlayout.parseinstance(testdemo).toprintable());
        }
    }
}

 

 运行结果:

main lock ing
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           5a ad 00 b0 (01011010 10101101 00000000 10110000) (-1342132902)
      4     4        (object header)                           cf 7f 00 00 (11001111 01111111 00000000 00000000) (32719)
      8     4        (object header)                           a0 c1 00 f8 (10100000 11000001 00000000 11111000) (-134168160)
     12     4        (loss due to the next object alignment)
instance size: 16 bytes
space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 
 
t1 lock ing
com.boke.testdemo object internals:
offset  size   type description                               value
      0     4        (object header)                           5a ad 00 b0 (01011010 10101101 00000000 10110000) (-1342132902)
      4     4        (object header)                           cf 7f 00 00 (11001111 01111111 00000000 00000000) (32719)
      8     4        (object header)                           a0 c1 00 f8 (10100000 11000001 00000000 11111000) (-134168160)
     12     4        (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 虚拟机会进入重量级锁的释放过程,唤醒因竞争该锁而被阻塞了的线程

 


 
到此为止本篇就讲完了锁的膨胀过程
java并发笔记四之synchronized 锁的膨胀过程(锁的升级过程)深入剖析

 

 
总结一下
  1. 偏向锁只会在第一次请求时采用 cas 操作,在锁对象的标记字段中记录下当前线程的地址。在之后的运行过程中,持有该偏向锁的线程的加锁操作将直接返回。它针对的是锁仅会被同一线程持有的情况。
  2. 轻量级锁采用 cas 操作,将锁对象的标记字段替换为一个指针,指向当前线程栈上的一块空间,存储着锁对象原本的标记字段。它针对的是多个线程在不同时间段申请同一把锁的情况。
  3. 重量级锁会阻塞、唤醒请求加锁的线程。它针对的是多个线程同时竞争同一把锁的情况。java 虚拟机采取了自适应自旋,来避免线程在面对非常小的 synchronized 代码块时,仍会被阻塞、唤醒的情况。
 

 
 
说完了锁的膨胀过程,那么会不会有锁的降级呢?
 
我在hotspot源码中找到了这样的注释:
// we create a list of in-use monitors for each thread.
//
// deflate_thread_local_monitors() scans a single thread's in-use list, while
// deflate_idle_monitors() scans only a global list of in-use monitors which
// is populated only as a thread dies (see omflush()).
//
// these operations are called at all safepoints, immediately after mutators
// are stopped, but before any objects have moved. collectively they traverse
// the population of in-use monitors, deflating where possible. the scavenged
// monitors are returned to the monitor free list.
//
// beware that we scavenge at *every* stop-the-world point. having a large
// number of monitors in-use could negatively impact performance. we also want
// to minimize the total # of monitors in circulation, as they incur a small
// footprint penalty.
//
// perversely, the heap size -- and thus the stw safepoint rate --
// typically drives the scavenge rate.  large heaps can mean infrequent gc,
// which in turn can mean large(r) numbers of objectmonitors in circulation.
// 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)的时间。
 
  原创不易,转载请标明出处,谢谢