1. 并发中锁的原理

64位虚拟机对象头 (markword占12字节96bit,Klass Word为4字节32bit。没有开启指针压缩后各占64bit)

截屏2021-05-17 下午3.53.57.png

1.1 导入jol依赖包

  1. <!-- https://mvnrepository.com/artifact/org.openjdk.jol/jol-core -->
  2. <dependency>
  3. <groupId>org.openjdk.jol</groupId>
  4. <artifactId>jol-core</artifactId>
  5. <version>0.10</version>
  6. </dependency>

1.2 查看相关参数

  1. public class Test3 {
  2. public static void main(String[] args) {
  3. // 查看jvm信息
  4. System.out.println(VM.current().details());
  5. System.out.println("===========");
  6. System.out.println(ClassLayout.parseClass(A.class).toPrintable());
  7. }
  8. }
  9. class A {
  10. boolean flag = true;
  11. }

结果:

  1. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  2. # Running 64-bit HotSpot VM.
  3. # Using compressed oop with 3-bit shift.
  4. # Using compressed klass with 3-bit shift.
  5. # WARNING | Compressed references base/shifts are guessed by the experiment!
  6. # WARNING | Therefore, computed addresses are just guesses, and ARE NOT RELIABLE.
  7. # WARNING | Make sure to attach Serviceability Agent to get the reliable addresses.
  8. # Objects are 8 bytes aligned.
  9. # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
  10. # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
  11. ===========
  12. com.ll.ch8.A object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  15. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  16. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253) 存字节码的文件地址
  17. 12 1 boolean A.flag true
  18. 13 3 (loss due to the next object alignment)
  19. Instance size: 16 bytes
  20. Space losses: 0 bytes internal + 3 bytes external = 3 bytes total

Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
对应:[Oop(Ordinary Object Pointer), boolen, byte, char, short,int, float, long ,double ]的大小

1.3 jvm计算后的hash参数

  1. public static void main(String[] args) {
  2. A a = new A();
  3. // 没计算hashcode对象头
  4. System.out.println("before hash:");
  5. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  6. // JVM计算hashcode的对象头
  7. System.out.println("-------jvm------0x" + Integer.toHexString(a.hashCode()));
  8. // 计算完成之后的对象头变化信息
  9. System.out.println("after hash:");
  10. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  11. }
  12. class A{
  13. }
  1. before hash:
  2. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  3. com.ll.ch8.A object internals:
  4. OFFSET SIZE TYPE DESCRIPTION VALUE
  5. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  6. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  7. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  8. 12 4 (loss due to the next object alignment)
  9. Instance size: 16 bytes
  10. Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  11. -------jvm------0x1c6b6478
  12. after hash:
  13. com.ll.ch8.A object internals:
  14. OFFSET SIZE TYPE DESCRIPTION VALUE
  15. 0 4 (object header) 01 78 64 6b (00000001 01111000 01100100 01101011) (1801746433)
  16. 4 4 (object header) 1c 00 00 00 (00011100 00000000 00000000 00000000) (28)
  17. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  18. 12 4 (loss due to the next object alignment)
  19. Instance size: 16 bytes
  20. Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

1-10行是jvm计算hashcode之前的信息,13-21行是计算后的信息。16-17行一共是8位,记录了markdown的信息,18行记录了对应字节码的地址(实例数据),19行为padding(对其填充)
第26位到第56位保存的hashcode值(25位没有使用)(小端存储:数据的高字节存储在高地址中,数据的低字节存储在低地址中)图中是倒着来的

  1. 十六进制:1c6b6478
  2. OFFSET SIZE VALUE
  3. 0 4 01 78 64 6b (00000001 01111000 01100100 01101011) (1801746433)
  4. 4 4 1c 00 00 00 (00011100 00000000 00000000 00000000) (28)

即 01111000 01100100 01101011 00011100 00000000 00000000 00000000 这7个字节是存小端信息的
剩下1个字节记录了:第1位没有使用、第2-5位记录了分代年龄、第6位记录了偏向锁状态、第7-8位记录了锁的状态标志.
截屏2021-05-17 下午4.18.12.png





偏向锁状态 1位 锁的状态 2位
未使用 25位 哈希值 31位 未使用 1位 GC年龄 4位 0 01 无锁
偏向线程信息 54位 epoch(记录撤销次数) 2位 未使用 1位 GC年龄 4位 1 01 偏向锁
线程持有锁的记录 62位 00 轻量级锁
monitor锁的信息 62位 10 重量级锁
—— 11 GC标志

1.4 偏向锁

1.4.1 偏向锁内容

  • 如果开启了偏向锁(默认是开启的),那么对象刚创建之后,Mark Word 最后三位的值101,并且这是它的 Thread,epoch,age 都是 0 ,在加锁的时候进行设置这些的值.
  • 偏向锁默认是延迟的(4s),不会在程序启动的时候立刻生效,如果想避免延迟,可以添加虚拟机参数来禁用延迟:-XX:BiasedLockingStartupDelay=0 来禁用延迟
  • 为什么要延迟:启动程序的时候jvm会启动很多线程,其中有带sync的,如果上来就是偏向锁,出现竞争的话会有消除偏向锁升级等情况,会影响性能。
  • 处于偏向锁的对象解锁后,线程 id 仍存储于对象头中

    举例

  • 正常情况下 ```java public static void main(String[] args) throws InterruptedException {

  1. A a = new A();
  2. synchronized (a) {
  3. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  4. }
  5. }
  1. ```
  2. 90 19 8d 0b (10010000 00011001 10001101 00001011)

可以看到是轻量级锁。

  • 延迟情况下:

    1. public static void main(String[] args) throws InterruptedException {
    2. Thread.sleep(5000);
    3. A a = new A();
    4. // sleep和new的过程不能反过来,否则就是轻量级锁了。默认是延迟开启的,如果先new的话,jvm就认为他是不可偏向的
    5. synchronized (a) {
    6. // System.out.println(ClassLayout.parseInstance(a).toPrintable());
    7. }
    8. // 效果一样
    9. System.out.println(ClassLayout.parseInstance(a).toPrintable());
    10. }

    延迟启动5s下,可以看到是偏向锁

    1. 05 98 80 3a (00000101 10011000 10000000 00111010)

    1.4.2 注意

  • 如果在偏向锁启动后,给对象加锁之前,对象不是无锁而已经是偏向锁的解释:这种情况谁也不偏向,叫做匿名偏向,处于可偏向状态(没有存偏向线程id),所以结论:我们刚刚new出来的对象,如果偏向锁启动是匿名偏向,没有启动就是普通对象。旨在告诉jvm我现在是可偏向的,可以加偏向锁。

  • 处于偏向锁的对象解锁后,线程 id 仍存储于对象头中 ```java //-XX:BiasedLockingStartupDelay=0 public class Test7 { static A a;

    public static void main(String[] args) {

    1. a= new A();
    2. System.out.println("before lock");
    3. System.out.println(ClassLayout.parseInstance(a).toPrintable());
    4. synchronized (a){
    5. System.out.println("locking");
    6. System.out.println(ClassLayout.parseInstance(a).toPrintable());
    7. }
    8. System.out.println("after lock");
    9. System.out.println(ClassLayout.parseInstance(a).toPrintable());

    }

}

  1. ```java
  2. before lock
  3. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  4. com.ll.ch8.A object internals:
  5. OFFSET SIZE TYPE DESCRIPTION VALUE
  6. 0 4 (object header) 05 00 00 00 (00000101 00000000 00000000 00000000) (5)
  7. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  8. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  9. 12 4 int A.i 0
  10. Instance size: 16 bytes
  11. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  12. locking
  13. com.ll.ch8.A object internals:
  14. OFFSET SIZE TYPE DESCRIPTION VALUE
  15. 0 4 (object header) 05 90 80 92 (00000101 10010000 10000000 10010010) (-1837068283)
  16. 4 4 (object header) c7 7f 00 00 (11000111 01111111 00000000 00000000) (32711)
  17. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  18. 12 4 int A.i 0
  19. Instance size: 16 bytes
  20. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  21. after lock
  22. com.ll.ch8.A object internals:
  23. OFFSET SIZE TYPE DESCRIPTION VALUE
  24. 0 4 (object header) 05 90 80 92 (00000101 10010000 10000000 10010010) (-1837068283)
  25. 4 4 (object header) c7 7f 00 00 (11000111 01111111 00000000 00000000) (32711)
  26. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  27. 12 4 int A.i 0
  28. Instance size: 16 bytes
  29. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

before lock时,第5行是偏向锁,但是没有偏向线程id,属于匿名偏向;locking时第15行偏向锁,存储了偏向线程id;after lock 第25行 锁释放了依然是偏向锁,依然存着偏向线程id

1.4.3 偏向锁与轻量级锁的性能对比

  • 轻量级锁: ```java public class Test6 {

    public static void main(String[] args) {

    1. A a = new A();
    2. long start = System.currentTimeMillis();
    3. for (int i = 0; i < 100000000; i++) {
    4. a.parse();
    5. }
    6. long end = System.currentTimeMillis();
    7. System.out.println( (end - start) + " ms");

    } }

class A { int i = 0;

  1. public synchronized void parse(){
  2. i++;
  3. }

}

  1. ![截屏2021-05-17 下午5.14.01.png](https://cdn.nlark.com/yuque/0/2021/png/12943861/1621242847322-bbcd97f5-0a0f-46e1-a08b-ead299ed47d7.png#clientId=ud925e247-86d8-4&from=drop&id=u98a75807&margin=%5Bobject%20Object%5D&name=%E6%88%AA%E5%B1%8F2021-05-17%20%E4%B8%8B%E5%8D%885.14.01.png&originHeight=42&originWidth=190&originalType=binary&ratio=1&size=8145&status=done&style=none&taskId=udb354871-08a0-40f7-8ae7-15f37376be3)
  2. - 改成偏向锁,使用虚拟机参数-XX:BiasedLockingStartupDelay=0
  3. ![截屏2021-05-17 下午5.13.38.png](https://cdn.nlark.com/yuque/0/2021/png/12943861/1621242822125-d02fc42c-4c8c-4d14-971c-4c78ee05ce98.png#clientId=ud925e247-86d8-4&from=drop&id=u310af6d1&margin=%5Bobject%20Object%5D&name=%E6%88%AA%E5%B1%8F2021-05-17%20%E4%B8%8B%E5%8D%885.13.38.png&originHeight=64&originWidth=182&originalType=binary&ratio=1&size=7751&status=done&style=none&taskId=u7f8a86a8-bffb-4053-8a29-1a2614bddc6)
  4. - 重量级锁
  5. ```java
  6. public class Test8 {
  7. public static void main(String[] args) throws InterruptedException {
  8. CountDownLatch countDownLatch = new CountDownLatch(100000000);
  9. A a = new A();
  10. long start = System.currentTimeMillis();
  11. for (int i = 0; i < 2; i++) {
  12. new Thread(()->{
  13. while (countDownLatch.getCount() > 0){
  14. a.parse();
  15. countDownLatch.countDown();
  16. }
  17. }).start();
  18. }
  19. countDownLatch.await();
  20. long end = System.currentTimeMillis();
  21. System.out.println((end - start) + " ms");
  22. }
  23. }
  24. class A {
  25. int i = 0;
  26. public synchronized void parse(){
  27. i++;
  28. }
  29. }

截屏2021-05-17 下午5.36.53.png

1.4.4 撤销偏向

以下几种情况会使对象的偏向锁失效

  1. 调用对象的 hashCode 方法
  1. public class Test10 {
  2. public static void main(String[] args) throws InterruptedException {
  3. TimeUnit.SECONDS.sleep(5);
  4. A a = new A();
  5. a.hashCode();
  6. System.out.println("before lock...");
  7. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  8. synchronized (a) {
  9. System.out.println("locking");
  10. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  11. }
  12. System.out.println("after locking");
  13. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  14. }
  15. }
  1. before lock...
  2. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  3. com.ll.ch8.A object internals:
  4. OFFSET SIZE TYPE DESCRIPTION VALUE
  5. 0 4 (object header) 01 6b 7c 94 (00000001 01101011 01111100 10010100) (-1803785471)
  6. 4 4 (object header) 63 00 00 00 (01100011 00000000 00000000 00000000) (99)
  7. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  8. 12 4 int A.i 0
  9. Instance size: 16 bytes
  10. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  11. locking
  12. com.ll.ch8.A object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. 0 4 (object header) 90 e9 86 0b (10010000 11101001 10000110 00001011) (193390992)
  15. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  16. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  17. 12 4 int A.i 0
  18. Instance size: 16 bytes
  19. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  20. after locking
  21. com.ll.ch8.A object internals:
  22. OFFSET SIZE TYPE DESCRIPTION VALUE
  23. 0 4 (object header) 01 6b 7c 94 (00000001 01101011 01111100 10010100) (-1803785471)
  24. 4 4 (object header) 63 00 00 00 (01100011 00000000 00000000 00000000) (99)
  25. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  26. 12 4 int A.i 0
  27. Instance size: 16 bytes
  28. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

调用hashcode方法后,会避免成为偏向锁。可以看到。延迟5秒时候第15行不会变成偏向锁101,而是轻量级锁00。hashcode与偏向锁是互斥的。

  1. 多个线程使用该对象

  2. 调用了 wait/notify 方法(调用wait方法会导致锁膨胀而使用重量级锁)

  1. public class Test10 {
  2. public static void main(String[] args) throws InterruptedException {
  3. TimeUnit.SECONDS.sleep(5);
  4. A a = new A();
  5. System.out.println("before lock...");
  6. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  7. new Thread(()->{
  8. synchronized (a) {
  9. System.out.println("locking");
  10. System.out.println("before wait");
  11. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  12. try {
  13. a.wait();
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. System.out.println("after wait");
  18. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  19. }
  20. }, "t1").start();
  21. TimeUnit.SECONDS.sleep(7);
  22. synchronized (a){
  23. a.notifyAll();
  24. }
  25. }
  26. }
  1. before lock...
  2. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  3. com.ll.ch8.A object internals:
  4. OFFSET SIZE TYPE DESCRIPTION VALUE
  5. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  6. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  7. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  8. 12 4 int A.i 0
  9. Instance size: 16 bytes
  10. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  11. locking
  12. before wait
  13. com.ll.ch8.A object internals:
  14. OFFSET SIZE TYPE DESCRIPTION VALUE
  15. 0 4 (object header) 00 89 e6 04 (00000000 10001001 11100110 00000100) (82217216)
  16. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  17. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  18. 12 4 int A.i 0
  19. Instance size: 16 bytes
  20. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  21. after wait
  22. com.ll.ch8.A object internals:
  23. OFFSET SIZE TYPE DESCRIPTION VALUE
  24. 0 4 (object header) fa 99 82 25 (11111010 10011001 10000010 00100101) (629316090)
  25. 4 4 (object header) 91 7f 00 00 (10010001 01111111 00000000 00000000) (32657)
  26. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  27. 12 4 int A.i 0
  28. Instance size: 16 bytes
  29. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

before lock时第5行无锁,before wait是第16行轻量级锁,after wait第26行重量级锁

1.4.5 重偏向问题

1. 单个对象偏向锁升级过程

如果线程是对一个对象加锁,不会发生重偏向情况。单个重偏向没有意义。因为每个线程加偏向锁都来cas判断对象的中的线程id是否是自己的,偏向锁释放后会保留偏向线程id,一直判断相当于轻量级锁。
如果两个线程交替执行(没有竞争),线程1持有对象a的偏向锁,当线程1释放偏向锁时,

  • 情况1:如果线程1已经死亡。另一个线程对对象a加锁,那么该锁膨胀为轻量级锁
  • 情况2:如果线程1还活着,另一个线程对对象a加锁,那么该锁依然膨胀为轻量级锁。

[注:其实个别情况下会发生偏向情况,但不是重偏向,还是偏向线程1]

情况1验证:线程1已经死亡

  1. // -XX:BiasedLockingStartupDelay=0
  2. @Slf4j(topic = "c.Test11")
  3. public class Test11 {
  4. public static void main(String[] args) throws InterruptedException {
  5. A a = new A();
  6. log.debug("before lock...");
  7. log.debug("{}", ClassLayout.parseInstance(a).toPrintable());
  8. new Thread(()->{
  9. synchronized (a) {
  10. log.debug("t1 locking");
  11. log.debug("{}", ClassLayout.parseInstance(a).toPrintable());
  12. }
  13. }, "t1").start();
  14. TimeUnit.SECONDS.sleep(10);
  15. synchronized (a){
  16. log.debug("main locking");
  17. log.debug("{}", ClassLayout.parseInstance(a).toPrintable());
  18. }
  19. }
  20. }
  1. 13:20:12.340 [main] DEBUG c.Test11 - before lock...
  2. 13:20:13.081 [main] DEBUG c.Test11 - com.ll.ch8.A object internals:
  3. OFFSET SIZE TYPE DESCRIPTION VALUE
  4. 0 4 (object header) 05 00 00 00 (00000101 00000000 00000000 00000000) (5)
  5. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  6. 8 4 (object header) 88 8e 01 f8 (10001000 10001110 00000001 11111000) (-134115704)
  7. 12 4 int A.i 0
  8. Instance size: 16 bytes
  9. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  10. 13:20:13.084 [t1] DEBUG c.Test11 - t1 locking
  11. 13:20:13.086 [t1] DEBUG c.Test11 - com.ll.ch8.A object internals:
  12. OFFSET SIZE TYPE DESCRIPTION VALUE
  13. 0 4 (object header) 05 10 0f 2b (00000101 00010000 00001111 00101011) (722407429)
  14. 4 4 (object header) c8 7f 00 00 (11001000 01111111 00000000 00000000) (32712)
  15. 8 4 (object header) 88 8e 01 f8 (10001000 10001110 00000001 11111000) (-134115704)
  16. 12 4 int A.i 0
  17. Instance size: 16 bytes
  18. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  19. 13:20:23.084 [main] DEBUG c.Test11 - main locking
  20. 13:20:23.086 [main] DEBUG c.Test11 - com.ll.ch8.A object internals:
  21. OFFSET SIZE TYPE DESCRIPTION VALUE
  22. 0 4 (object header) 90 b9 cc 01 (10010000 10111001 11001100 00000001) (30194064)
  23. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  24. 8 4 (object header) 88 8e 01 f8 (10001000 10001110 00000001 11111000) (-134115704)
  25. 12 4 int A.i 0
  26. Instance size: 16 bytes
  27. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

before lock…之前,第4行处于可偏向状态;t1 locking后,第14行,处于偏向t1状态;10s后main locking后,此时t1已经死亡,第24行,发生膨胀,处于轻量级锁状态。

情况2验证:线程1还活着

  1. @Slf4j(topic = "c.Test11")
  2. public class Test11 {
  3. public static void main(String[] args) throws InterruptedException {
  4. A a = new A();
  5. log.debug("before lock...");
  6. log.debug("{}", ClassLayout.parseInstance(a).toPrintable());
  7. new Thread(()->{
  8. synchronized (a) {
  9. log.debug("t1 locking");
  10. log.debug("{}", ClassLayout.parseInstance(a).toPrintable());
  11. }
  12. try {
  13. TimeUnit.SECONDS.sleep(15);
  14. log.debug("t1 end");
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }, "t1").start();
  19. TimeUnit.SECONDS.sleep(10);
  20. synchronized (a){
  21. log.debug("main locking");
  22. log.debug("{}", ClassLayout.parseInstance(a).toPrintable());
  23. }
  24. }
  25. }
  1. 13:25:15.155 [main] DEBUG c.Test11 - before lock...
  2. 13:25:15.871 [main] DEBUG c.Test11 - com.ll.ch8.A object internals:
  3. OFFSET SIZE TYPE DESCRIPTION VALUE
  4. 0 4 (object header) 05 00 00 00 (00000101 00000000 00000000 00000000) (5)
  5. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  6. 8 4 (object header) 88 8e 01 f8 (10001000 10001110 00000001 11111000) (-134115704)
  7. 12 4 int A.i 0
  8. Instance size: 16 bytes
  9. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  10. 13:25:15.874 [t1] DEBUG c.Test11 - t1 locking
  11. 13:25:15.877 [t1] DEBUG c.Test11 - com.ll.ch8.A object internals:
  12. OFFSET SIZE TYPE DESCRIPTION VALUE
  13. 0 4 (object header) 05 10 02 65 (00000101 00010000 00000010 01100101) (1694633989)
  14. 4 4 (object header) a2 7f 00 00 (10100010 01111111 00000000 00000000) (32674)
  15. 8 4 (object header) 88 8e 01 f8 (10001000 10001110 00000001 11111000) (-134115704)
  16. 12 4 int A.i 0
  17. Instance size: 16 bytes
  18. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  19. 13:25:25.878 [main] DEBUG c.Test11 - main locking
  20. 13:25:25.879 [main] DEBUG c.Test11 - com.ll.ch8.A object internals:
  21. OFFSET SIZE TYPE DESCRIPTION VALUE
  22. 0 4 (object header) 90 29 60 08 (10010000 00101001 01100000 00001000) (140519824)
  23. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  24. 8 4 (object header) 88 8e 01 f8 (10001000 10001110 00000001 11111000) (-134115704)
  25. 12 4 int A.i 0
  26. Instance size: 16 bytes
  27. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  28. 13:25:30.882 [t1] DEBUG c.Test11 - t1 end

第24行main locking的时候线程1还活着,发生膨胀,依然是轻量级锁状态。第31行,此时t1才死亡。

特别情况:单个对象还是会变成偏向锁,偏向线程1(尝试了N次之后)

  1. // -XX:BiasedLockingStartupDelay=0
  2. public class Test13 {
  3. public static void main(String[] args) throws InterruptedException {
  4. A a = new A();
  5. Thread t1 = new Thread(()->{
  6. synchronized (a){
  7. System.out.println("t1 locking");
  8. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  9. }
  10. }, "t1");
  11. t1.start();
  12. TimeUnit.SECONDS.sleep(5);
  13. System.out.println("t1 release");
  14. Thread t2= new Thread(()->{
  15. synchronized (a){
  16. System.out.println("t2 locking");
  17. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  18. }
  19. }, "t2");
  20. t2.start();
  21. TimeUnit.SECONDS.sleep(5);
  22. System.out.println("t2 release");
  23. Thread t3 = new Thread(()->{
  24. synchronized (a){
  25. System.out.println("t3 locking");
  26. System.out.println(ClassLayout.parseInstance(a).toPrintable());
  27. }
  28. }, "t3");
  29. t3.start();
  30. System.out.println("t3 release");
  31. }
  32. }
  1. t1 locking
  2. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  3. com.ll.ch8.A object internals:
  4. OFFSET SIZE TYPE DESCRIPTION VALUE
  5. 0 4 (object header) 05 c8 8e b9 (00000101 11001000 10001110 10111001) (-1181825019)
  6. 4 4 (object header) d9 7f 00 00 (11011001 01111111 00000000 00000000) (32729)
  7. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  8. 12 4 int A.i 0
  9. Instance size: 16 bytes
  10. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  11. t1 release
  12. t2 locking
  13. com.ll.ch8.A object internals:
  14. OFFSET SIZE TYPE DESCRIPTION VALUE
  15. 0 4 (object header) 05 c8 8e b9 (00000101 11001000 10001110 10111001) (-1181825019)
  16. 4 4 (object header) d9 7f 00 00 (11011001 01111111 00000000 00000000) (32729)
  17. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  18. 12 4 int A.i 0
  19. Instance size: 16 bytes
  20. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  21. t2 release
  22. t3 release
  23. t3 locking
  24. com.ll.ch8.A object internals:
  25. OFFSET SIZE TYPE DESCRIPTION VALUE
  26. 0 4 (object header) 05 c8 8e b9 (00000101 11001000 10001110 10111001) (-1181825019)
  27. 4 4 (object header) d9 7f 00 00 (11011001 01111111 00000000 00000000) (32729)
  28. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  29. 12 4 int A.i 0
  30. Instance size: 16 bytes
  31. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

第16行和第28行按理说应该是轻量级锁状态,在这里却变成了偏向锁。而且是偏向了同一个线程t1。cpu可能会给他分配同一个线程id。

2. 如何实现重偏向

使用同一个线程对同一个类的很多个对象加锁才会出现重偏向,而偏向锁中的epoch(时间戳)就是记录撤销次数的。 每个class会维护一个epoch,对象也会有该值(建对象时从class中拿),当该class的对象发生偏向撤销时,该计数器会+1,当达到20时,jvm就认为该class的偏向锁有问题,进行批量重偏向。不在同步块中的对象epoch != 当前的epoch,会失效,重偏向将线程id改成新的线程;在同步块中的对象会将其epoch值改成当前的epoch

  • 批量重偏向
    • 如果对象虽然被多个线程访问,但是线程间不存在竞争,这时偏向 t1 的对象仍有机会重新偏向 t2
      • 重偏向会重置Thread ID
    • 当撤销超过20次后(超过阈值,第20次开始),JVM 会觉得是不是偏向错了,这时会在给对象加锁时,不会撤销而是重新偏向至该加锁线程。
    • 分为两步:
      • 将类中的撤销计数器自增1,之后当该类已存在的实例获得锁时,就会尝试重偏向。
      • 处理当前正在被使用的锁对象,通过遍历所有存活线程的栈,找到所有正在使用的偏向锁对象,然后更新它们的epoch值。也就是说不会重偏向正在使用的锁,否则会破坏锁的线程安全性。
  • 批量重撤销
    • 当撤销偏向锁的阈值超过 40(第40次开始) 以后,就会将整个类的剩下的对象都改为不可偏向的,新建的对象也是不可偏向的
    • 两步:
      • 将类的偏向标记关闭,之后当该类已存在的实例获得锁时,就会升级为轻量级锁;该类新分配的对象的mark word则是无锁模式。
      • 处理当前正在被使用的锁对象,通过遍历所有存活线程的栈,找到所有正在使用的偏向锁对象,然后撤销偏向锁。
  • 整个过程

    • 当线程1对40个对象加偏向锁(101)后,存储该线程1的id, 线程2重新给这40个对象加锁,之后线程3再个这40个对象加锁
      • 线程2:
        • 前19个对象为撤销偏向,线程2加锁后由原先线程1的偏向锁升级为轻量级锁(00),同步代码块执行完成后变为正常状态(001);
        • 从第20个对象开始,达到阈值20,epoch设置为01,剩下的对象epoch还为00,进行批量重偏向,线程2加锁后由原先的线程1的偏向锁变为该线程的偏向锁(101),存储该线程2的id,同步代码块执行完成后状态不变;
      • 线程3:
        • 前19个对象已经是正常状态,执行加轻量锁(00)和释放锁(001)的。(该对象偏向锁已经失效)
        • 从第20个对象开始,撤销偏向,线程3加锁后由原先线程2的偏向锁升级为轻量级锁(00),同步代码块执行完成后变为正常状态(001);
        • 从第40个对象开始,达到了阈值40,剩下的对象会撤销偏向,由原先线程2的偏向锁升级为轻量级锁(00),同步代码块执行完成后变为正常状态(001);新建的对象会进入正常状态(001)

          代码示例

  • 第10次(第10个对象) ```java public class Test12 {

    public static void main(String[] args) throws InterruptedException {

    1. List<A> list= new ArrayList<>(50);
    2. Thread t1 = new Thread(()->{
    3. for (int i = 0; i < 10; i++) {
    4. A a = new A();
    5. list.add(a);
    6. synchronized (a){
    7. if (i == 9){
    8. System.out.println("t1 locking");
    9. System.out.println(ClassLayout.parseInstance(list.get(9)).toPrintable());
    10. } if (i == 9){
    11. System.out.println("t2 locking");
    12. System.out.println(ClassLayout.parseInstance(list.get(9)).toPrintable());
    13. }
    14. }
    15. }
    16. }, "t1");
    17. System.out.println("--------t1开始----------");
    18. t1.start();
    19. t1.join();
    20. System.out.println("--------t1结束----------");
    21. System.out.println(ClassLayout.parseInstance(list.get(9)).toPrintable());
    22. Thread t2 = new Thread(()->{
    23. for (int i = 0; i < list.size(); i++) {
    24. A a = list.get(i);
    25. synchronized (a){
    26. if (i == 9){
    27. System.out.println("t2 locking");
    28. System.out.println(ClassLayout.parseInstance(list.get(9)).toPrintable());
    29. }
    30. }
    31. }
    32. }, "t2");
    33. System.out.println("--------t2开始----------");
    34. t2.start();
    35. t2.join();
    36. System.out.println("--------t2结束----------");
    37. System.out.println(ClassLayout.parseInstance(list.get(9)).toPrintable());

    } }

  1. 结果:
  2. ```java
  3. --------t1开始----------
  4. t1 locking
  5. com.ll.ch8.A object internals:
  6. OFFSET SIZE TYPE DESCRIPTION VALUE
  7. 0 4 (object header) 05 f8 07 86 (00000101 11111000 00000111 10000110) (-2046298107)
  8. 4 4 (object header) ed 7f 00 00 (11101101 01111111 00000000 00000000) (32749)
  9. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  10. 12 4 int A.i 0
  11. Instance size: 16 bytes
  12. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  13. --------t1结束----------
  14. com.ll.ch8.A object internals:
  15. OFFSET SIZE TYPE DESCRIPTION VALUE
  16. 0 4 (object header) 05 f8 07 86 (00000101 11111000 00000111 10000110) (-2046298107)
  17. 4 4 (object header) ed 7f 00 00 (11101101 01111111 00000000 00000000) (32749)
  18. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  19. 12 4 int A.i 0
  20. Instance size: 16 bytes
  21. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  22. --------t2开始----------
  23. t2 locking
  24. com.ll.ch8.A object internals:
  25. OFFSET SIZE TYPE DESCRIPTION VALUE
  26. 0 4 (object header) f8 68 ef 10 (11111000 01101000 11101111 00010000) (284125432)
  27. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  28. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  29. 12 4 int A.i 0
  30. Instance size: 16 bytes
  31. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  32. --------t2结束----------
  33. com.ll.ch8.A object internals:
  34. OFFSET SIZE TYPE DESCRIPTION VALUE
  35. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  36. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  37. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  38. 12 4 int A.i 0
  39. Instance size: 16 bytes
  40. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

可以看到t1开始后第5行变成了偏向状态,t1结束后低15行依然是偏向状态,t2开始后,将其膨胀成了轻量级锁状态(26行),之后变成无锁状态(36行)(1-19都是这样,批量重撤销)

  • 第20次(第20个对象)

结果:

  1. --------t1开始----------
  2. t1 locking
  3. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  4. com.ll.ch8.A object internals:
  5. OFFSET SIZE TYPE DESCRIPTION VALUE
  6. 0 4 (object header) 05 e0 0b b6 (00000101 11100000 00001011 10110110) (-1240735739)
  7. 4 4 (object header) f2 7f 00 00 (11110010 01111111 00000000 00000000) (32754)
  8. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  9. 12 4 int A.i 0
  10. Instance size: 16 bytes
  11. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  12. --------t1结束----------
  13. com.ll.ch8.A object internals:
  14. OFFSET SIZE TYPE DESCRIPTION VALUE
  15. 0 4 (object header) 05 e0 0b b6 (00000101 11100000 00001011 10110110) (-1240735739)
  16. 4 4 (object header) f2 7f 00 00 (11110010 01111111 00000000 00000000) (32754)
  17. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  18. 12 4 int A.i 0
  19. Instance size: 16 bytes
  20. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  21. --------t2开始----------
  22. t2 locking
  23. com.ll.ch8.A object internals:
  24. OFFSET SIZE TYPE DESCRIPTION VALUE
  25. 0 4 (object header) 05 61 a0 b6 (00000101 01100001 10100000 10110110) (-1231003387)
  26. 4 4 (object header) f2 7f 00 00 (11110010 01111111 00000000 00000000) (32754)
  27. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  28. 12 4 int A.i 0
  29. Instance size: 16 bytes
  30. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  31. --------t2结束----------
  32. com.ll.ch8.A object internals:
  33. OFFSET SIZE TYPE DESCRIPTION VALUE
  34. 0 4 (object header) 05 61 a0 b6 (00000101 01100001 10100000 10110110) (-1231003387)
  35. 4 4 (object header) f2 7f 00 00 (11110010 01111111 00000000 00000000) (32754)
  36. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  37. 12 4 int A.i 0
  38. Instance size: 16 bytes
  39. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

可以看到第27行和37行依然是偏向锁,只不过偏向线程id改变了(20-39都会是这样,重新偏向该线程)

  • 第35次(第35个对象) ```java public class Test12 {

    public static void main(String[] args) throws InterruptedException {

    1. List<A> list= new ArrayList<>(50);
    2. Thread t1 = new Thread(()->{
    3. for (int i = 0; i < 50; i++) {
    4. A a = new A();
    5. list.add(a);
    6. synchronized (a){
    7. if (i == 35){
    8. System.out.println("t1 locking");
    9. System.out.println(ClassLayout.parseInstance(list.get(35)).toPrintable());
    10. }
    11. }
    12. }
    13. }, "t1");
    14. System.out.println("--------t1开始----------");
    15. t1.start();
    16. t1.join();
    17. System.out.println("--------t1结束----------");
    18. System.out.println(ClassLayout.parseInstance(list.get(35)).toPrintable());
    19. Thread t2 = new Thread(()->{
    20. for (int i = 0; i < list.size(); i++) {
    21. A a = list.get(i);
    22. synchronized (a){
    23. if (i == 35){
    24. System.out.println("t2 locking");
    25. System.out.println(ClassLayout.parseInstance(list.get(35)).toPrintable());
    26. }
    27. }
    28. }
    29. }, "t2");
    30. System.out.println("--------t2开始----------");
    31. t2.start();
    32. t2.join();
    33. System.out.println("--------t2结束----------");
    34. System.out.println(ClassLayout.parseInstance(list.get(35)).toPrintable());
  1. Thread t3 = new Thread(()->{
  2. for (int i = 0; i < list.size(); i++) {
  3. A a = list.get(i);
  4. synchronized (a){
  5. if (i == 35){
  6. System.out.println("t3 locking");
  7. System.out.println(ClassLayout.parseInstance(list.get(35)).toPrintable());
  8. }
  9. }
  10. }
  11. }, "t3");
  12. System.out.println("--------t3开始----------");
  13. t3.start();
  14. t3.join();
  15. System.out.println("--------t3结束----------");
  16. System.out.println(ClassLayout.parseInstance(list.get(35)).toPrintable());
  17. }

}

  1. ```java
  2. --------t1开始----------
  3. t1 locking
  4. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  5. com.ll.ch8.A object internals:
  6. OFFSET SIZE TYPE DESCRIPTION VALUE
  7. 0 4 (object header) 05 b0 83 9e (00000101 10110000 10000011 10011110) (-1635536891)
  8. 4 4 (object header) e4 7f 00 00 (11100100 01111111 00000000 00000000) (32740)
  9. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  10. 12 4 int A.i 0
  11. Instance size: 16 bytes
  12. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  13. --------t1结束----------
  14. com.ll.ch8.A object internals:
  15. OFFSET SIZE TYPE DESCRIPTION VALUE
  16. 0 4 (object header) 05 b0 83 9e (00000101 10110000 10000011 10011110) (-1635536891)
  17. 4 4 (object header) e4 7f 00 00 (11100100 01111111 00000000 00000000) (32740)
  18. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  19. 12 4 int A.i 0
  20. Instance size: 16 bytes
  21. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  22. --------t2开始----------
  23. t2 locking
  24. com.ll.ch8.A object internals:
  25. OFFSET SIZE TYPE DESCRIPTION VALUE
  26. 0 4 (object header) 05 19 09 9e (00000101 00011001 00001001 10011110) (-1643570939)
  27. 4 4 (object header) e4 7f 00 00 (11100100 01111111 00000000 00000000) (32740)
  28. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  29. 12 4 int A.i 0
  30. Instance size: 16 bytes
  31. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  32. --------t2结束----------
  33. com.ll.ch8.A object internals:
  34. OFFSET SIZE TYPE DESCRIPTION VALUE
  35. 0 4 (object header) 05 19 09 9e (00000101 00011001 00001001 10011110) (-1643570939)
  36. 4 4 (object header) e4 7f 00 00 (11100100 01111111 00000000 00000000) (32740)
  37. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  38. 12 4 int A.i 0
  39. Instance size: 16 bytes
  40. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  41. --------t3开始----------
  42. t3 locking
  43. com.ll.ch8.A object internals:
  44. OFFSET SIZE TYPE DESCRIPTION VALUE
  45. 0 4 (object header) f8 f8 0e 10 (11111000 11111000 00001110 00010000) (269416696)
  46. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  47. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  48. 12 4 int A.i 0
  49. Instance size: 16 bytes
  50. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  51. --------t3结束----------
  52. com.ll.ch8.A object internals:
  53. OFFSET SIZE TYPE DESCRIPTION VALUE
  54. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  55. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  56. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  57. 12 4 int A.i 0
  58. Instance size: 16 bytes
  59. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

可以看到6,16行偏向线程t1;27行,37行偏向线程t2;48行开始膨胀成轻量级锁。

2 锁的膨胀机制

2.1 锁的膨胀过程举例

  1. public class Test9 {
  2. public static void main(String[] args) throws InterruptedException {
  3. A a = new A();
  4. System.out.println("------before lock------");
  5. System.out.println(ClassLayout.parseInstance(a).toPrintable()); //无锁
  6. Thread t1 = new Thread(()->{
  7. synchronized (a) {
  8. try {
  9. System.out.println("------t1 locking------");
  10. System.out.println(ClassLayout.parseInstance(a).toPrintable()); // 轻量级锁
  11. TimeUnit.SECONDS.sleep(5);
  12. System.out.println("------t1 release------");
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }, "t1");
  18. t1.start();
  19. TimeUnit.SECONDS.sleep(1);
  20. synchronized (a){
  21. System.out.println("------main locking------");
  22. System.out.println(ClassLayout.parseInstance(a).toPrintable()); // 重量级锁
  23. System.out.println("------main release------");
  24. }
  25. System.out.println("------after lock------");
  26. System.out.println(ClassLayout.parseInstance(a).toPrintable()); // 重量级锁
  27. System.gc();
  28. System.out.println("------after gc------");
  29. System.out.println(ClassLayout.parseInstance(a).toPrintable()); // 无锁,GC加1
  30. }
  31. }
  1. ------before lock------
  2. # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  3. com.ll.ch8.A object internals:
  4. OFFSET SIZE TYPE DESCRIPTION VALUE
  5. 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
  6. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  7. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  8. 12 4 int A.i 0
  9. Instance size: 16 bytes
  10. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  11. ------t1 locking------
  12. com.ll.ch8.A object internals:
  13. OFFSET SIZE TYPE DESCRIPTION VALUE
  14. 0 4 (object header) 00 c9 6c 10 (00000000 11001001 01101100 00010000) (275564800)
  15. 4 4 (object header) 00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
  16. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  17. 12 4 int A.i 0
  18. Instance size: 16 bytes
  19. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  20. ------t1 release------
  21. ------main locking------
  22. com.ll.ch8.A object internals:
  23. OFFSET SIZE TYPE DESCRIPTION VALUE
  24. 0 4 (object header) 4a 5f 81 85 (01001010 01011111 10000001 10000101) (-2055119030)
  25. 4 4 (object header) f9 7f 00 00 (11111001 01111111 00000000 00000000) (32761)
  26. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  27. 12 4 int A.i 0
  28. Instance size: 16 bytes
  29. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  30. ------main release------
  31. ------after lock------
  32. com.ll.ch8.A object internals:
  33. OFFSET SIZE TYPE DESCRIPTION VALUE
  34. 0 4 (object header) 4a 5f 81 85 (01001010 01011111 10000001 10000101) (-2055119030)
  35. 4 4 (object header) f9 7f 00 00 (11111001 01111111 00000000 00000000) (32761)
  36. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  37. 12 4 int A.i 0
  38. Instance size: 16 bytes
  39. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
  40. ------after gc------
  41. com.ll.ch8.A object internals:
  42. OFFSET SIZE TYPE DESCRIPTION VALUE
  43. 0 4 (object header) 09 00 00 00 (00001001 00000000 00000000 00000000) (9)
  44. 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
  45. 8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
  46. 12 4 int A.i 0
  47. Instance size: 16 bytes
  48. Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

注意在gc过后,值为00001001,其中gc年龄为0001,发生了变化。

2.2 偏向锁升级

匿名偏向状态是偏向锁的初始状态,在这个状态下第一个试图获取该对象的锁的线程,会使用CAS操作(汇编命令CMPXCHG)尝试将自己的threadID写入对象头的mark word中,使匿名偏向状态升级为已偏向(Biased)的偏向锁状态。在已偏向状态下,线程指针threadID非空,且偏向锁的时间戳epoch为有效值。
如果之后有线程再次尝试获取锁时,需要检查mark word中存储的threadID是否与自己相同即可,如果相同那么表示当前线程已经获得了对象的锁,不需要再使用CAS操作来进行加锁。
如果mark word中存储的threadID与当前线程不同,那么将执行CAS操作,试图将当前线程的ID替换mark word中的threadID。只有当对象处于下面两种状态中时,才可以执行成功:

  • 对象处于匿名偏向状态
  • 对象处于可重偏向(Rebiasable)状态,新线程可使用CAS将threadID指向自己

如果对象不处于上面两个状态,说明锁存在线程竞争,在CAS替换失败后会执行偏向锁撤销操作。偏向锁的撤销需要等待全局安全点Safe Point(安全点是 jvm为了保证在垃圾回收的过程中引用关系不会发生变化设置的安全状态,在这个状态上会暂停所有线程工作),在这个安全点会挂起获得偏向锁的线程。
在暂停线程后,会通过遍历当前jvm的所有线程的方式,检查持有偏向锁的线程状态是否存活:

  • 如果线程还存活,且线程正在执行同步代码块中的代码,则升级为轻量级锁
  • 如果持有偏向锁的线程未存活,或者持有偏向锁的线程未在执行同步代码块中的代码,则进行校验是否允许重偏向:
    • 不允许重偏向,则撤销偏向锁,将mark word升级为轻量级锁,进行CAS竞争锁
    • 允许重偏向,设置为匿名偏向锁状态,CAS将偏向锁重新指向新线程
  • 完成上面的操作后,唤醒暂停的线程,从安全点继续执行代码

    3. 可重入锁

    3.1 说明

  • 可重入锁又名递归锁是指在同一个线程在外层方法获取锁的时候,再进入该线程的内层方法会自动获取锁(前提,锁对象得是同一个对象),不会因为之前已经获取过还没释放而阻塞。

  • Java中ReentrantLock和synchronized都是可重入锁,可重入锁的一个优点是可一定程度避免死锁。
  • 一个线程中的多个流程可以获取同一把锁,持有这把同步锁可以再次进入。即自己可以获取自己的内部锁。

    3.2 种类

  • 隐式锁(即synchronized关键字使用的锁)默认是可重入锁

  • 显式锁(即Lock)也有ReentrantLock这样的可重入锁。(reentrantLock注意加了几次锁,就要释放几次锁,否则容易造成死锁别的线程拿不到)