synchronized(this) { /* 临界区 */ }
// 等价于
synchronized (this) { /* 临界区 */ }
// 实例方法加 synchronized 修饰符等价于 synchronized(this) 包裹方法体
Lock Record,CAS 將 Mark Word 指向 Lock Record,自旋等待。ObjectMonitor(C++ 實現,基於 OS Mutex/Condition Variable),線程進入 _WaitSet / _EntryList 掛起/喚醒。ObjectMonitor 實現互斥。| 維度 | synchronized(this) | synchronized 實例方法 |
|---|---|---|
| 鎖對象 | 當前實例 | 當前實例 |
| 粒度控制 | 可縮小臨界區範圍 | 整個方法體 |
| 可讀性 | 顯式意圖清晰 | 隱式,易忽略 |
synchronized(list) 後 list = new ArrayList() 導致鎖失效。ReentrantLock、ConcurrentHashMap、LongAdder 等無鎖/細粒度鎖組件,性能更優、API 更豐富。tryLock(timeout)、避免嵌套鎖。理解 Mark Word、鎖升級、Monitor、JMM 語義,是從「會用 synchronized」進階到「能調優併發」的必經之路。