按照如下代码进行测试,理论上同步代码块里应该对对象添加偏向锁,可是为什么从输出上来看,添加的是轻量锁呢
public static void test(){
Object o = new Object();
System.out.println(ClassLayout.parseInstance(o).toPrintable());
synchronized (o){
System.out.println(ClassLayout.parseInstance(o).toPrintable());
}
System.out.println(ClassLayout.parseInstance(o).toPrintable());
}
java.lang.Object 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) e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243)
java.lang.Object object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) b0 f4 70 01 (10110000 11110100 01110000 00000001) (24179888)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243)
java.lang.Object 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) e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243)
1
git00ll OP 自问自答一下,是因为 jvm 在加载过程中会暂时禁用偏向锁,所以此处只有轻量级锁。
可以在调用 test 方法之前,先休眠 5 秒,这样等 jvm 完全加载完成后,偏向锁才能生效,就能看到效果了。 |
2
sagaxu 2020-09-15 21:35:41 +08:00 via Android
JDK15 开始已经默认禁用偏向锁,未来版本会移除这个功能
|
3
HiShan 2020-09-16 09:46:24 +08:00
别学了,都被弃用了
|