0%

java | Monitor 概念

讲一下 Java 中的 Monitor

对象头

32 为虚拟机为例。

普通对象

1
2
3
4
5
6
7
|------------------------------------------|
| Object Header(64 bits) |
|------------------------------------------|
| | |
| Mark Word(32 bits)| Klass Word(32 bits) |
| | |
|------------------------------------------|
  • Mark Word
    • 参考下面的解析
  • Klass Word
    • 指针,指向了这个对象存储的 class

Mark Word

下面的 state 代表 4 种状态,而 Mark Word 一共是 32bits

1
2
3
4
5
6
7
8
9
10
11
12
13
|-----------------------------------------------|-------------------|
| Mark Word(32 bits) | State |
|-------------------------------------------------------------------|
| hashcode: 25 |age: 4 | biased_lock:0| 01| Normal |
|-------------------------------------------------------------------|
| thread:23 |epoch:2 |age: 4 | biased_lock:1| 01| Biased |
|-------------------------------------------------------------------|
| ptr_to_lock_record: 30 | 00| Lightweight Locked|
|-------------------------------------------------------------------|
| ptr_to_heavyweight_monitor:30| 10| Heavyweight Locked|
|-------------------------------------------------------------------|
| | 11| Marker for GC |
|-------------------------------------------------------------------|
  • biased_locked 是否启用偏向锁
  • Lightweight 00
    • 轻量级锁
  • Heavyweight 10
    • 重量级锁

这个状态要结合

数组对象

1
2
3
4
5
6
7
|---------------------------------------------------------------------|
| Object Header(96 bits) |
|---------------------------------------------------------------------|
| | | |
| Mark Word(32 bits)| Klass Word(32 bits) | array length (32 bits) |
| | | |
|---------------------------------------------------------------------|
请我喝杯咖啡吧~