1. 引言
在 Java 并发编程中,synchronized 是最基础、也最容易被"用错"的同步手段。很多人对它的认知停留在"加锁、互斥、性能差"这几个标签上,却说不清它到底锁了什么、JVM 在字节码层面做了什么、为什么 JDK 6 之后它不再"慢"。
本文从字节码指令 出发,一路讲到对象头 Mark Word 、Monitor 结构 ,再到 偏向锁 → 轻量级锁 → 重量级锁的升级过程,最后给出实际使用中的注意事项。读完你应该能回答:
synchronized修饰方法和修饰代码块,底层实现有什么不同?- 锁信息到底存在哪里?为什么说"锁的是对象"?
- 锁升级是怎么发生的?偏向锁为什么会被废弃?
2. 基本语义:synchronized 到底锁了什么
synchronized 提供的是互斥 与可见性两重语义:
- 互斥:同一时刻只有一个线程能进入被同步的临界区。
- 可见性 :线程释放锁时,会把工作内存中的共享变量刷新到主内存;获取锁时会清空工作内存,从主内存重新读取。这等价于一次
volatile的读写屏障效果。
锁的对象取决于写法:
| 写法 | 锁对象 |
|---|---|
synchronized 修饰实例方法 |
当前实例 this |
synchronized 修饰静态方法 |
当前类的 Class 对象 |
synchronized (obj) 代码块 |
括号中的 obj 对象 |
java
public class LockDemo {
// 锁的是 this
public synchronized void instanceMethod() { }
// 锁的是 LockDemo.class
public static synchronized void staticMethod() { }
private final Object lock = new Object();
public void blockMethod() {
// 锁的是 lock 对象
synchronized (lock) {
// 临界区
}
}
}
一个常见误区:锁的是对象,不是代码 。两个线程分别调用同一个实例的 instanceMethod() 会互斥;但如果是两个不同实例,则互不影响------因为它们锁的是不同的 this。
3. 字节码层面:monitorenter 与 monitorexit
3.1 同步代码块
用 javap -v 反编译上面的 blockMethod(),可以看到关键指令:
text
public void blockMethod();
Code:
0: aload_0
1: getfield #7 // Field lock:Ljava/lang/Object;
4: dup
5: astore_1
6: monitorenter
7: aload_1
8: monitorexit
9: goto 17
12: astore_2
13: aload_1
14: monitorexit
15: aload_2
16: athrow
17: return
Exception table:
from to target type
7 9 12 any
7 16 12 any
要点:
monitorenter进入临界区,monitorexit退出。- 出现了两次
monitorexit:一次是正常路径,一次在异常路径(Exception table覆盖了临界区)。这保证了即使临界区抛异常,锁也一定会释放,不会造成死锁。 - 编译器会自动生成
try-finally结构,finally中执行monitorexit。
3.2 同步方法
同步方法没有 monitorenter/monitorexit 指令,而是通过方法访问标志 ACC_SYNCHRONIZED 来标识:
text
public synchronized void instanceMethod();
descriptor: ()V
flags: ACC_PUBLIC, ACC_SYNCHRONIZED
JVM 在方法调用时检查该标志,若存在则先获取 Monitor,方法执行完(含异常退出)后释放。语义与代码块一致,只是实现路径不同。
4. Monitor:锁的实现载体
monitorenter 操作的对象是 Monitor (也叫管程/监视器)。在 HotSpot 中,Monitor 由 C++ 的 ObjectMonitor 实现,核心字段包括:
cpp
class ObjectMonitor {
volatile markOop _header; // 对象头 Mark Word 的备份
void* volatile _owner; // 持有锁的线程
volatile intptr_t _count; // 重入次数
ObjectWaiter* volatile _EntryList; // 阻塞等待的线程队列
ObjectWaiter* volatile _WaitSet; // 调用 wait() 的线程集合
// ...
};
monitorenter 的语义可以简化为:
- 若 Monitor 的
_owner为空,尝试 CAS 把当前线程写入_owner,成功则获得锁,_count = 1。 - 若
_owner就是当前线程,说明是重入 ,_count++。 - 否则进入
_EntryList阻塞等待,直到被唤醒后重新竞争。
monitorexit 则执行 _count--,减到 0 时清空 _owner 并唤醒 _EntryList 中的线程。
#mermaid-svg-jH5qDelZcnwEaowk{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-jH5qDelZcnwEaowk .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-jH5qDelZcnwEaowk .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-jH5qDelZcnwEaowk .error-icon{fill:#552222;}#mermaid-svg-jH5qDelZcnwEaowk .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-jH5qDelZcnwEaowk .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-jH5qDelZcnwEaowk .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-jH5qDelZcnwEaowk .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-jH5qDelZcnwEaowk .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-jH5qDelZcnwEaowk .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-jH5qDelZcnwEaowk .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-jH5qDelZcnwEaowk .marker{fill:#333333;stroke:#333333;}#mermaid-svg-jH5qDelZcnwEaowk .marker.cross{stroke:#333333;}#mermaid-svg-jH5qDelZcnwEaowk svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-jH5qDelZcnwEaowk p{margin:0;}#mermaid-svg-jH5qDelZcnwEaowk .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-jH5qDelZcnwEaowk .cluster-label text{fill:#333;}#mermaid-svg-jH5qDelZcnwEaowk .cluster-label span{color:#333;}#mermaid-svg-jH5qDelZcnwEaowk .cluster-label span p{background-color:transparent;}#mermaid-svg-jH5qDelZcnwEaowk .label text,#mermaid-svg-jH5qDelZcnwEaowk span{fill:#333;color:#333;}#mermaid-svg-jH5qDelZcnwEaowk .node rect,#mermaid-svg-jH5qDelZcnwEaowk .node circle,#mermaid-svg-jH5qDelZcnwEaowk .node ellipse,#mermaid-svg-jH5qDelZcnwEaowk .node polygon,#mermaid-svg-jH5qDelZcnwEaowk .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-jH5qDelZcnwEaowk .rough-node .label text,#mermaid-svg-jH5qDelZcnwEaowk .node .label text,#mermaid-svg-jH5qDelZcnwEaowk .image-shape .label,#mermaid-svg-jH5qDelZcnwEaowk .icon-shape .label{text-anchor:middle;}#mermaid-svg-jH5qDelZcnwEaowk .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-jH5qDelZcnwEaowk .rough-node .label,#mermaid-svg-jH5qDelZcnwEaowk .node .label,#mermaid-svg-jH5qDelZcnwEaowk .image-shape .label,#mermaid-svg-jH5qDelZcnwEaowk .icon-shape .label{text-align:center;}#mermaid-svg-jH5qDelZcnwEaowk .node.clickable{cursor:pointer;}#mermaid-svg-jH5qDelZcnwEaowk .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-jH5qDelZcnwEaowk .arrowheadPath{fill:#333333;}#mermaid-svg-jH5qDelZcnwEaowk .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-jH5qDelZcnwEaowk .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-jH5qDelZcnwEaowk .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-jH5qDelZcnwEaowk .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-jH5qDelZcnwEaowk .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-jH5qDelZcnwEaowk .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-jH5qDelZcnwEaowk .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-jH5qDelZcnwEaowk .cluster text{fill:#333;}#mermaid-svg-jH5qDelZcnwEaowk .cluster span{color:#333;}#mermaid-svg-jH5qDelZcnwEaowk div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-jH5qDelZcnwEaowk .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-jH5qDelZcnwEaowk rect.text{fill:none;stroke-width:0;}#mermaid-svg-jH5qDelZcnwEaowk .icon-shape,#mermaid-svg-jH5qDelZcnwEaowk .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-jH5qDelZcnwEaowk .icon-shape p,#mermaid-svg-jH5qDelZcnwEaowk .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-jH5qDelZcnwEaowk .icon-shape .label rect,#mermaid-svg-jH5qDelZcnwEaowk .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-jH5qDelZcnwEaowk .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-jH5qDelZcnwEaowk .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-jH5qDelZcnwEaowk :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是
否
是
否
monitorenter
_owner 是否为空
CAS 抢占 _owner
_count = 1,获得锁
_owner 是否为当前线程
_count++,重入
进入 _EntryList 阻塞
被唤醒后重新竞争
5. 对象头与 Mark Word
锁状态信息并不在 Monitor 里"凭空存在",而是与对象头紧密绑定。HotSpot 对象在内存中的布局分为三部分:
- 对象头(Header):Mark Word + 类型指针(Klass Pointer)
- 实例数据(Instance Data)
- 对齐填充(Padding)
其中 Mark Word 是理解锁升级的关键。在 64 位 JVM 下它占 8 字节(64 bit),内容随锁状态动态复用:
| 锁状态 | Mark Word 内容(简化) |
|---|---|
| 无锁 | unused(25) | hashCode(31) | unused(1) | 分代年龄(4) | 0 | 01 |
| 偏向锁 | 线程 ID(54) | Epoch(2) | unused(1) | 分代年龄(4) | 1 | 01 |
| 轻量级锁 | 指向栈中锁记录的指针(62) | 00 |
| 重量级锁 | 指向 Monitor 的指针(62) | 10 |
| GC 标记 | 空(62) | 11 |
可以看到,最后 2 bit 是锁标志位 ,JVM 正是靠它判断当前对象处于哪种锁状态。同一块 64 bit 空间在不同状态下被"复用"存放不同信息,这也是为什么偏向锁会与 hashCode 冲突------一旦对象计算过 identity hash,就无法再进入偏向状态。
6. 锁升级:偏向锁 → 轻量级锁 → 重量级锁
JDK 6 对 synchronized 做了大量优化,引入了锁升级机制,让锁的开销随竞争程度"按需增长"。
6.1 偏向锁
适用场景 :绝大多数情况下,锁不仅没有多线程竞争,而且始终由同一个线程反复获取。
过程:
- 线程首次获取锁时,用 CAS 把自己的线程 ID 写入 Mark Word,并把标志位设为
01。 - 之后同一线程再次进入,只需比较 Mark Word 中的线程 ID 是否为自己,无需任何 CAS 操作,直接进入。
撤销 :一旦有另一个线程尝试获取,偏向模式立即失效,需要撤销偏向(revoke),通常在安全点(safepoint)进行,代价较高。
注意:偏向锁在 JDK 15 起默认关闭(JEP 374),JDK 18 起相关实现被移除。原因是偏向锁的撤销需要 STW,在高并发场景下收益有限而维护成本高。面试中若被问到,应说明这一演进。
6.2 轻量级锁
适用场景 :多个线程交替获取锁,但几乎没有同时竞争(无真正并发冲突)。
过程:
- 线程在栈帧中分配一个 Lock Record(锁记录),把对象 Mark Word 复制进去(称为 Displaced Mark Word)。
- 用 CAS 尝试把 Mark Word 更新为指向该 Lock Record 的指针 ,标志位设为
00。 - CAS 成功 → 获得轻量级锁;CAS 失败 → 说明存在竞争,膨胀为重量级锁。
解锁:用 CAS 把 Displaced Mark Word 写回对象头,若失败说明锁已被膨胀,需走重量级锁的释放流程。
6.3 重量级锁
适用场景 :多个线程同时竞争同一把锁。
此时 Mark Word 指向 ObjectMonitor,未抢到锁的线程进入 _EntryList 并被挂起(park) ,涉及操作系统内核态切换,开销最大。这也是早期 synchronized 被诟病"慢"的根本原因。
6.4 升级路径总览
#mermaid-svg-dJoLoIfmM2irxS5b{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-dJoLoIfmM2irxS5b .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-dJoLoIfmM2irxS5b .error-icon{fill:#552222;}#mermaid-svg-dJoLoIfmM2irxS5b .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-dJoLoIfmM2irxS5b .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-dJoLoIfmM2irxS5b .marker{fill:#333333;stroke:#333333;}#mermaid-svg-dJoLoIfmM2irxS5b .marker.cross{stroke:#333333;}#mermaid-svg-dJoLoIfmM2irxS5b svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-dJoLoIfmM2irxS5b p{margin:0;}#mermaid-svg-dJoLoIfmM2irxS5b .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-dJoLoIfmM2irxS5b .cluster-label text{fill:#333;}#mermaid-svg-dJoLoIfmM2irxS5b .cluster-label span{color:#333;}#mermaid-svg-dJoLoIfmM2irxS5b .cluster-label span p{background-color:transparent;}#mermaid-svg-dJoLoIfmM2irxS5b .label text,#mermaid-svg-dJoLoIfmM2irxS5b span{fill:#333;color:#333;}#mermaid-svg-dJoLoIfmM2irxS5b .node rect,#mermaid-svg-dJoLoIfmM2irxS5b .node circle,#mermaid-svg-dJoLoIfmM2irxS5b .node ellipse,#mermaid-svg-dJoLoIfmM2irxS5b .node polygon,#mermaid-svg-dJoLoIfmM2irxS5b .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-dJoLoIfmM2irxS5b .rough-node .label text,#mermaid-svg-dJoLoIfmM2irxS5b .node .label text,#mermaid-svg-dJoLoIfmM2irxS5b .image-shape .label,#mermaid-svg-dJoLoIfmM2irxS5b .icon-shape .label{text-anchor:middle;}#mermaid-svg-dJoLoIfmM2irxS5b .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-dJoLoIfmM2irxS5b .rough-node .label,#mermaid-svg-dJoLoIfmM2irxS5b .node .label,#mermaid-svg-dJoLoIfmM2irxS5b .image-shape .label,#mermaid-svg-dJoLoIfmM2irxS5b .icon-shape .label{text-align:center;}#mermaid-svg-dJoLoIfmM2irxS5b .node.clickable{cursor:pointer;}#mermaid-svg-dJoLoIfmM2irxS5b .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-dJoLoIfmM2irxS5b .arrowheadPath{fill:#333333;}#mermaid-svg-dJoLoIfmM2irxS5b .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-dJoLoIfmM2irxS5b .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-dJoLoIfmM2irxS5b .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-dJoLoIfmM2irxS5b .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-dJoLoIfmM2irxS5b .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-dJoLoIfmM2irxS5b .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-dJoLoIfmM2irxS5b .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-dJoLoIfmM2irxS5b .cluster text{fill:#333;}#mermaid-svg-dJoLoIfmM2irxS5b .cluster span{color:#333;}#mermaid-svg-dJoLoIfmM2irxS5b div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-dJoLoIfmM2irxS5b .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-dJoLoIfmM2irxS5b rect.text{fill:none;stroke-width:0;}#mermaid-svg-dJoLoIfmM2irxS5b .icon-shape,#mermaid-svg-dJoLoIfmM2irxS5b .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-dJoLoIfmM2irxS5b .icon-shape p,#mermaid-svg-dJoLoIfmM2irxS5b .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-dJoLoIfmM2irxS5b .icon-shape .label rect,#mermaid-svg-dJoLoIfmM2irxS5b .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-dJoLoIfmM2irxS5b .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-dJoLoIfmM2irxS5b .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-dJoLoIfmM2irxS5b :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 另一线程竞争
CAS 失败/竞争加剧
调用 hashCode
无锁 01
偏向锁 01
轻量级锁 00
重量级锁 10
需要强调:锁只能升级,不能降级(偏向锁撤销后回到无锁是特例)。一旦膨胀为重量级锁,即使后续竞争消失,也不会退回轻量级锁。
7. 代码示例:验证锁的互斥与重入
java
public class SyncDemo {
private int count = 0;
// 可重入:同一线程可多次进入
public synchronized void reentrant() {
System.out.println("第一次进入");
reentrantInner();
}
private synchronized void reentrantInner() {
System.out.println("重入成功,count = " + count);
}
public static void main(String[] args) throws InterruptedException {
SyncDemo demo = new SyncDemo();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
demo.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
demo.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("最终 count = " + demo.count); // 期望 2000
}
public synchronized void increment() {
count++;
}
}
运行结果稳定为 2000,说明互斥生效。若去掉 synchronized,count++ 的"读-改-写"三步非原子,结果通常小于 2000。
8. 使用建议与常见坑
- 锁粒度尽量小 :只把真正需要互斥的代码放进
synchronized块,避免把 I/O、日志等耗时操作包进去。 - 避免锁字符串常量或包装类型 :
synchronized ("abc")或synchronized (Integer.valueOf(1))可能锁到全局共享对象(字符串常量池、Integer缓存),导致意外的跨模块互斥。 - 锁对象用
private final:防止锁对象被外部替换或置空,导致同步失效。 - 注意死锁 :多把锁时保持一致的加锁顺序;尽量用
tryLock(ReentrantLock)设置超时。 - 不要用
synchronized保护volatile已能解决的场景 :单纯可见性需求用volatile更轻量。 - 高并发场景考虑
ReentrantLock:它支持公平锁、可中断、超时、多条件变量,灵活性更高;synchronized的优势是语法简单、自动释放、JVM 持续优化。
9. 总结
synchronized代码块编译为monitorenter/monitorexit,方法则通过ACC_SYNCHRONIZED标志实现,二者语义一致。- 锁的载体是 Monitor(ObjectMonitor) ,对象头 Mark Word 记录锁状态,最后 2 bit 是锁标志位。
- JDK 6 引入偏向锁 → 轻量级锁 → 重量级锁的升级机制,让锁开销随竞争程度增长;偏向锁已在 JDK 15 默认关闭、JDK 18 移除。
- 锁只能升级不能降级,理解这一点有助于判断性能瓶颈。
- 实际使用中关注锁粒度、锁对象选择与死锁风险,必要时切换到
ReentrantLock。
理解字节码与对象头,才算真正理解 synchronized------它不是一个"黑盒关键字",而是一套由编译器、JVM 与操作系统协同完成的同步机制。