我们都知道synchronized的关键字,锁住的是对象头,可是却无法直接的看到到底改变了什么,那么openjdk提供了jol可以直接查看到对象头的改变。
1.引入依赖
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
2.打印对象头
public class JolDemo {
static A a = new A();
public static void main(String[] args) {
System.out.println(Integer.toHexString(a.hashCode()));
System.out.println(ClassLayout.parseInstance(a).toPrintable());
}
}
3.展示结果
2d6d8735
# 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
com.example.demo.jol.A object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 35 87 6d (00000001 00110101 10000111 01101101) (1837577473)
4 4 (object header) 2d 00 00 00 (00101101 00000000 00000000 00000000) (45)
8 4 (object header) 92 c3 00 f8 (10010010 11000011 00000000 11111000) (-134167662)
12 4 int A.a 0
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
可以看到object header中包含了hashcode及锁的信息。