<!-- https://mvnrepository.com/artifact/org.openjdk.jol/jol-core -->
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
package learn.cn.多線程;
/**
* create by liuzhiwei on 2020/4/2
*/
public class JavaObjectHead {
//boolean flag;//1 byte
int flag;//4 byte
}
package learn.cn.多線程;
import org.openjdk.jol.info.ClassLayout;
/**
* create by liuzhiwei on 2020/4/2
* Java對象頭 64位虛擬機
* <p>
* 對象頭 mark word 4Byte 32bits 實際上 12byte=96bit 周志明第二版2008年出版的(32位虛擬機)
* mark word (64bit) + klass pointer/Class MetaData address(32bit/64bit(無壓縮) = 12Byte
* <p>
* 實例變量
* 對齊填充
* 8Bytes 的倍數
* <p>
* 哈希碼 GC標記 GC次數 同步鎖標記 偏向鎖持有者
* <p>
* synchronized對象狀態
* 無狀態
* 偏向鎖
* 輕量鎖
* 重量鎖
* gc標記
*/
public class JavaObjectHeadTest {
public static void main(String[] args) {
JavaObjectHead head = new JavaObjectHead();
System.out.println(head.hashCode());//大端小端存儲
System.out.println(Integer.toHexString(head.hashCode()));//大端小端存儲
System.out.println(ClassLayout.parseInstance(head).toPrintable());
synchronized (head) {
System.out.println("加鎖");
}
}
}
1.3.jar:/Users/liuzhiwei/.m2/repository/org/openjdk/jol/jol-core/0.9/jol-core-0.9.jar learn.cn.多線程.JavaObjectHeadTest
1725154839
66d3c617
# 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
learn.cn.多線程.JavaObjectHead object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 17 c6 d3 (00000001 00010111 11000110 11010011) (-741992703)
4 4 (object header) 66 00 00 00 (01100110 00000000 00000000 00000000) (102)
8 4 (object header) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253)
12 4 int JavaObjectHead.flag 0
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
加鎖
Process finished with exit code 0
Synchronized鎖對象 普通對象 類對象
Synchronized(Object) 不能用String Long Integer 常量 Object 爲null
可重入 父子類
獨佔鎖
悲觀鎖
鎖升級(對象頭 markword)
- 無鎖
- 偏向鎖:第一個線程 偏向第一個線程
如果有多個線程競爭的時候升級爲輕量級鎖
可以關閉偏向鎖,默認開啓 -XX:+UseBiasedLocking
關閉偏向鎖- 輕量級 自旋鎖(CAS 自旋10次 消耗cpu計算資源): (加鎖代碼)執行時間短 線程數少 lockrecord 將markword 複製到lockrecord
- 重量級鎖(操作系統內核鎖 排隊 不消耗cpu計算資源): 執行時間長 線程數多