synchronized锁升级之路: 从无锁到偏向锁再到重量级锁,JVM到底在优化什么 - root

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站 👁️ 300 次阅读

synchronized锁升级之路: 从无锁到偏向锁再到重量级锁,JVM到底在优化什么

引言: synchronized从重量级到智能化的演进

曾几何时,Java开发者谈synchronized色变,将其视为性能瓶颈的代名词,纷纷转向ReentrantLock等并发工具。然而随着JDK 1.6的发布,JVM团队对synchronized进行了史诗级优化,引入了锁升级机制,使其性能在多数场景下已经不输于Lock体系。

这个锁升级过程被称为锁膨胀(Lock Inflation)或锁粗化(Lock Coarsening)的逆过程,实际上是JVM根据锁竞争情况,在偏向锁、轻量级锁、重量级锁之间动态切换的智能优化。本文将深入剖析这一机制的底层原理。

一、Java对象头: 锁存在的物理基础

1.1 Mark Word: 锁信息的载体

锁状态的所有秘密都隐藏在Java对象头的Mark Word中。Mark Word在不同锁状态下存储的内容不同:

#publish-mermaid-1784691747332-0{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;}}#publish-mermaid-1784691747332-0 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747332-0 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747332-0 .error-icon{fill:#552222;}#publish-mermaid-1784691747332-0 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747332-0 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747332-0 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747332-0 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747332-0 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747332-0 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747332-0 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747332-0 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747332-0 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747332-0 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747332-0 p{margin:0;}#publish-mermaid-1784691747332-0 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#publish-mermaid-1784691747332-0 .cluster-label text{fill:#333;}#publish-mermaid-1784691747332-0 .cluster-label span{color:#333;}#publish-mermaid-1784691747332-0 .cluster-label span p{background-color:transparent;}#publish-mermaid-1784691747332-0 .label text,#publish-mermaid-1784691747332-0 span{fill:#333;color:#333;}#publish-mermaid-1784691747332-0 .node rect,#publish-mermaid-1784691747332-0 .node circle,#publish-mermaid-1784691747332-0 .node ellipse,#publish-mermaid-1784691747332-0 .node polygon,#publish-mermaid-1784691747332-0 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747332-0 .rough-node .label text,#publish-mermaid-1784691747332-0 .node .label text,#publish-mermaid-1784691747332-0 .image-shape .label,#publish-mermaid-1784691747332-0 .icon-shape .label{text-anchor:middle;}#publish-mermaid-1784691747332-0 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#publish-mermaid-1784691747332-0 .rough-node .label,#publish-mermaid-1784691747332-0 .node .label,#publish-mermaid-1784691747332-0 .image-shape .label,#publish-mermaid-1784691747332-0 .icon-shape .label{text-align:center;}#publish-mermaid-1784691747332-0 .node.clickable{cursor:pointer;}#publish-mermaid-1784691747332-0 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#publish-mermaid-1784691747332-0 .arrowheadPath{fill:#333333;}#publish-mermaid-1784691747332-0 .edgePath .path{stroke:#333333;stroke-width:1px;}#publish-mermaid-1784691747332-0 .flowchart-link{stroke:#333333;fill:none;}#publish-mermaid-1784691747332-0 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747332-0 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747332-0 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747332-0 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#publish-mermaid-1784691747332-0 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#publish-mermaid-1784691747332-0 .cluster text{fill:#333;}#publish-mermaid-1784691747332-0 .cluster span{color:#333;}#publish-mermaid-1784691747332-0 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;}#publish-mermaid-1784691747332-0 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1784691747332-0 rect.text{fill:none;stroke-width:0;}#publish-mermaid-1784691747332-0 .icon-shape,#publish-mermaid-1784691747332-0 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747332-0 .icon-shape p,#publish-mermaid-1784691747332-0 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#publish-mermaid-1784691747332-0 .icon-shape .label rect,#publish-mermaid-1784691747332-0 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747332-0 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#publish-mermaid-1784691747332-0 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#publish-mermaid-1784691747332-0 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747332-0 [data-look="neo"].node rect,#publish-mermaid-1784691747332-0 [data-look="neo"].cluster rect,#publish-mermaid-1784691747332-0 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747332-0 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747332-0 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747332-0 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747332-0 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747332-0 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747332-0 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747332-0 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747332-0 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747332-0 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}不同锁状态下的Mark Word无锁: unused:25 | hashcode:31 | unused:1 | age:4 | 0 | 01偏向锁: threadId:54 | epoch:2 | unused:1 | age:4 | 1 | 01轻量级锁: 指向栈中锁记录的指针:62 | 00重量级锁: 指向重量级锁的指针:62 | 10GC标记: CMS标记信息:62 | 11Mark Word结构 (64位JVM)锁标志位: 2bit偏向锁标志: 1bit存储内容: 其余61bit

1.2 查看对象头的工具代码

import org.openjdk.jol.info.ClassLayout;

public class MarkWordDemo {

public static void main(String[] args) {

// 无锁状态

Object obj = new Object();

System.out.println("=== 无锁状态 ===");

System.out.println(ClassLayout.parseInstance(obj).toPrintable());

// 偏向锁状态

synchronized (obj) {

System.out.println("\n=== 偏向锁状态 ===");

System.out.println(ClassLayout.parseInstance(obj).toPrintable());

}

// 轻量级锁状态(通过竞争触发)

Thread t1 = new Thread(() ->{

synchronized (obj) {

System.out.println("\n=== 线程1持有偏向锁 ===");

System.out.println(ClassLayout.parseInstance(obj).toPrintable());

}

});

t1.start();

Thread t2 = new Thread(() ->{

synchronized (obj) {

System.out.println("\n=== 线程2竞争,触发轻量级锁 ===");

System.out.println(ClassLayout.parseInstance(obj).toPrintable());

}

});

t2.start();

}

}

二、锁升级全景图: 从无锁到重量级锁

2.1 完整升级路径

#publish-mermaid-1784691747386-1{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;}}#publish-mermaid-1784691747386-1 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747386-1 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747386-1 .error-icon{fill:#552222;}#publish-mermaid-1784691747386-1 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747386-1 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747386-1 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747386-1 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747386-1 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747386-1 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747386-1 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747386-1 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747386-1 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747386-1 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747386-1 p{margin:0;}#publish-mermaid-1784691747386-1 defs [id$="-barbEnd"]{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747386-1 g.stateGroup text{fill:#9370DB;stroke:none;font-size:10px;}#publish-mermaid-1784691747386-1 g.stateGroup text{fill:#333;stroke:none;font-size:10px;}#publish-mermaid-1784691747386-1 g.stateGroup .state-title{font-weight:bolder;fill:#131300;}#publish-mermaid-1784691747386-1 g.stateGroup rect{fill:#ECECFF;stroke:#9370DB;}#publish-mermaid-1784691747386-1 g.stateGroup line{stroke:#333333;stroke-width:1;}#publish-mermaid-1784691747386-1 .transition{stroke:#333333;stroke-width:1;fill:none;}#publish-mermaid-1784691747386-1 .stateGroup .composit{fill:white;border-bottom:1px;}#publish-mermaid-1784691747386-1 .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px;}#publish-mermaid-1784691747386-1 .state-note{stroke:#aaaa33;fill:#fff5ad;}#publish-mermaid-1784691747386-1 .state-note text{fill:black;stroke:none;font-size:10px;}#publish-mermaid-1784691747386-1 .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#publish-mermaid-1784691747386-1 .edgeLabel .label rect{fill:#ECECFF;opacity:0.5;}#publish-mermaid-1784691747386-1 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747386-1 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747386-1 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747386-1 .edgeLabel .label text{fill:#333;}#publish-mermaid-1784691747386-1 .label div .edgeLabel{color:#333;}#publish-mermaid-1784691747386-1 .stateLabel text{fill:#131300;font-size:10px;font-weight:bold;}#publish-mermaid-1784691747386-1 .node circle.state-start{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747386-1 .node .fork-join{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747386-1 .node circle.state-end{fill:#9370DB;stroke:white;stroke-width:1.5;}#publish-mermaid-1784691747386-1 .end-state-inner{fill:white;stroke-width:1.5;}#publish-mermaid-1784691747386-1 .node rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747386-1 .node polygon{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747386-1 [id$="-barbEnd"]{fill:#333333;}#publish-mermaid-1784691747386-1 .statediagram-cluster rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747386-1 .cluster-label,#publish-mermaid-1784691747386-1 .nodeLabel{color:#131300;}#publish-mermaid-1784691747386-1 .statediagram-cluster rect.outer{rx:5px;ry:5px;}#publish-mermaid-1784691747386-1 .statediagram-state .divider{stroke:#9370DB;}#publish-mermaid-1784691747386-1 .statediagram-state .title-state{rx:5px;ry:5px;}#publish-mermaid-1784691747386-1 .statediagram-cluster.statediagram-cluster .inner{fill:white;}#publish-mermaid-1784691747386-1 .statediagram-cluster.statediagram-cluster-alt .inner{fill:#f0f0f0;}#publish-mermaid-1784691747386-1 .statediagram-cluster .inner{rx:0;ry:0;}#publish-mermaid-1784691747386-1 .statediagram-state rect.basic{rx:5px;ry:5px;}#publish-mermaid-1784691747386-1 .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#f0f0f0;}#publish-mermaid-1784691747386-1 .note-edge{stroke-dasharray:5;}#publish-mermaid-1784691747386-1 .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#publish-mermaid-1784691747386-1 .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#publish-mermaid-1784691747386-1 .statediagram-note text{fill:black;}#publish-mermaid-1784691747386-1 .statediagram-note .nodeLabel{color:black;}#publish-mermaid-1784691747386-1 .statediagram .edgeLabel{color:red;}#publish-mermaid-1784691747386-1 [id$="-dependencyStart"],#publish-mermaid-1784691747386-1 [id$="-dependencyEnd"]{fill:#333333;stroke:#333333;stroke-width:1;}#publish-mermaid-1784691747386-1 .statediagramTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1784691747386-1 [data-look="neo"].statediagram-cluster rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1;}#publish-mermaid-1784691747386-1 [data-look="neo"].statediagram-cluster rect.outer{rx:5px;ry:5px;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747386-1 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747386-1 [data-look="neo"].node rect,#publish-mermaid-1784691747386-1 [data-look="neo"].cluster rect,#publish-mermaid-1784691747386-1 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747386-1 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747386-1 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747386-1 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747386-1 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747386-1 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747386-1 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747386-1 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747386-1 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747386-1 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}第一个线程获取锁另一个线程竞争竞争加剧/自旋失败无锁偏向锁轻量级锁重量级锁Mark Word标志位: 001Mark Word标志位: 101记录持有线程IDMark Word标志位: 00指向栈中锁记录Mark Word标志位: 10指向monitor对象

2.2 锁升级决策树

#publish-mermaid-1784691747489-2{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;}}#publish-mermaid-1784691747489-2 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747489-2 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747489-2 .error-icon{fill:#552222;}#publish-mermaid-1784691747489-2 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747489-2 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747489-2 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747489-2 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747489-2 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747489-2 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747489-2 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747489-2 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747489-2 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747489-2 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747489-2 p{margin:0;}#publish-mermaid-1784691747489-2 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#publish-mermaid-1784691747489-2 .cluster-label text{fill:#333;}#publish-mermaid-1784691747489-2 .cluster-label span{color:#333;}#publish-mermaid-1784691747489-2 .cluster-label span p{background-color:transparent;}#publish-mermaid-1784691747489-2 .label text,#publish-mermaid-1784691747489-2 span{fill:#333;color:#333;}#publish-mermaid-1784691747489-2 .node rect,#publish-mermaid-1784691747489-2 .node circle,#publish-mermaid-1784691747489-2 .node ellipse,#publish-mermaid-1784691747489-2 .node polygon,#publish-mermaid-1784691747489-2 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747489-2 .rough-node .label text,#publish-mermaid-1784691747489-2 .node .label text,#publish-mermaid-1784691747489-2 .image-shape .label,#publish-mermaid-1784691747489-2 .icon-shape .label{text-anchor:middle;}#publish-mermaid-1784691747489-2 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#publish-mermaid-1784691747489-2 .rough-node .label,#publish-mermaid-1784691747489-2 .node .label,#publish-mermaid-1784691747489-2 .image-shape .label,#publish-mermaid-1784691747489-2 .icon-shape .label{text-align:center;}#publish-mermaid-1784691747489-2 .node.clickable{cursor:pointer;}#publish-mermaid-1784691747489-2 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#publish-mermaid-1784691747489-2 .arrowheadPath{fill:#333333;}#publish-mermaid-1784691747489-2 .edgePath .path{stroke:#333333;stroke-width:1px;}#publish-mermaid-1784691747489-2 .flowchart-link{stroke:#333333;fill:none;}#publish-mermaid-1784691747489-2 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747489-2 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747489-2 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747489-2 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#publish-mermaid-1784691747489-2 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#publish-mermaid-1784691747489-2 .cluster text{fill:#333;}#publish-mermaid-1784691747489-2 .cluster span{color:#333;}#publish-mermaid-1784691747489-2 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;}#publish-mermaid-1784691747489-2 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1784691747489-2 rect.text{fill:none;stroke-width:0;}#publish-mermaid-1784691747489-2 .icon-shape,#publish-mermaid-1784691747489-2 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747489-2 .icon-shape p,#publish-mermaid-1784691747489-2 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#publish-mermaid-1784691747489-2 .icon-shape .label rect,#publish-mermaid-1784691747489-2 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747489-2 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#publish-mermaid-1784691747489-2 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#publish-mermaid-1784691747489-2 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747489-2 [data-look="neo"].node rect,#publish-mermaid-1784691747489-2 [data-look="neo"].cluster rect,#publish-mermaid-1784691747489-2 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747489-2 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747489-2 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747489-2 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747489-2 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747489-2 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747489-2 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747489-2 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747489-2 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747489-2 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}否成功失败是否是是否成功失败线程请求锁对象是否处于偏向锁?CAS修改Mark Word获得轻量级锁自旋等待偏向线程是否存活?CAS将偏向锁指向当前线程偏向线程是否退出同步?撤销偏向锁自旋是否成功?膨胀为重量级锁升级为轻量级锁保持偏向锁

三、偏向锁(Biased Locking): 消除无竞争同步开销

3.1 核心思想

偏向锁是JDK 1.6引入的最激进优化: 如果一个锁总是被同一个线程获取,那么就让这个线程在获取锁时免除同步操作。

public class BiasedLockingDemo {

// JVM参数: -XX:+UseBiasedLocking -XX:BiasedLockingStartupDelay=0

public static void main(String[] args) throws InterruptedException {

// 偏向锁有启动延迟(默认4秒),生产环境中JVM启动后通常已开启

Thread.sleep(5000);

Object lock = new Object();

// 第一次获取锁: 安装偏向锁

synchronized (lock) {

System.out.println("第一次获取锁后Mark Word:");

System.out.println(ClassLayout.parseInstance(lock).toPrintable());

}

// 第二次获取锁: 直接使用偏向锁,无需CAS

synchronized (lock) {

System.out.println("第二次获取锁后Mark Word:");

System.out.println(ClassLayout.parseInstance(lock).toPrintable());

}

// 其他线程竞争: 偏向锁撤销

Thread competitor = new Thread(() ->{

synchronized (lock) {

System.out.println("竞争线程获取锁后Mark Word:");

System.out.println(ClassLayout.parseInstance(lock).toPrintable());

}

});

competitor.start();

competitor.join();

System.out.println("竞争结束后Mark Word:");

System.out.println(ClassLayout.parseInstance(lock).toPrintable());

}

}

3.2 偏向锁的获取与撤销流程

JVM线程2锁对象线程1JVM线程2锁对象线程1#publish-mermaid-1784691747627-3{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;}}#publish-mermaid-1784691747627-3 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747627-3 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747627-3 .error-icon{fill:#552222;}#publish-mermaid-1784691747627-3 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747627-3 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747627-3 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747627-3 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747627-3 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747627-3 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747627-3 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747627-3 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747627-3 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747627-3 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747627-3 p{margin:0;}#publish-mermaid-1784691747627-3 .actor{stroke:#9370DB;fill:#ECECFF;stroke-width:1;}#publish-mermaid-1784691747627-3 rect.actor.outer-path[data-look="neo"]{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 rect.note[data-look="neo"]{stroke:#aaaa33;fill:#fff5ad;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 text.actor>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747627-3 .actor-line{stroke:#9370DB;}#publish-mermaid-1784691747627-3 .innerArc{stroke-width:1.5;stroke-dasharray:none;}#publish-mermaid-1784691747627-3 .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#publish-mermaid-1784691747627-3 .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#publish-mermaid-1784691747627-3 [id$="-arrowhead"] path{fill:#333;stroke:#333;}#publish-mermaid-1784691747627-3 .sequenceNumber{fill:white;}#publish-mermaid-1784691747627-3 [id$="-sequencenumber"]{fill:#333;}#publish-mermaid-1784691747627-3 [id$="-crosshead"] path{fill:#333;stroke:#333;}#publish-mermaid-1784691747627-3 .messageText{fill:#333;stroke:none;}#publish-mermaid-1784691747627-3 .labelBox{stroke:#9370DB;fill:#ECECFF;filter:none;}#publish-mermaid-1784691747627-3 .labelText,#publish-mermaid-1784691747627-3 .labelText>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747627-3 .loopText,#publish-mermaid-1784691747627-3 .loopText>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747627-3 .sectionTitle,#publish-mermaid-1784691747627-3 .sectionTitle>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747627-3 .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:#9370DB;fill:#9370DB;}#publish-mermaid-1784691747627-3 .note{stroke:#aaaa33;fill:#fff5ad;}#publish-mermaid-1784691747627-3 .noteText,#publish-mermaid-1784691747627-3 .noteText>tspan{fill:black;stroke:none;font-weight:normal;}#publish-mermaid-1784691747627-3 .activation0{fill:#f4f4f4;stroke:#666;}#publish-mermaid-1784691747627-3 .activation1{fill:#f4f4f4;stroke:#666;}#publish-mermaid-1784691747627-3 .activation2{fill:#f4f4f4;stroke:#666;}#publish-mermaid-1784691747627-3 .actorPopupMenu{position:absolute;}#publish-mermaid-1784691747627-3 .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#publish-mermaid-1784691747627-3 .actor-man circle,#publish-mermaid-1784691747627-3 line{fill:#ECECFF;stroke-width:2px;}#publish-mermaid-1784691747627-3 g rect.rect{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));stroke:#9370DB;}#publish-mermaid-1784691747627-3 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747627-3 [data-look="neo"].node rect,#publish-mermaid-1784691747627-3 [data-look="neo"].cluster rect,#publish-mermaid-1784691747627-3 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747627-3 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747627-3 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747627-3 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747627-3 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747627-3 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}获取偏向锁可偏向(01)无ThreadId偏向锁(101)ThreadId=T1再次获取ThreadId==T1竞争导致撤销alt[T1已退出同步][T1仍在同步]检查Mark WordCAS设置ThreadId获取锁成功检查Mark Word直接获取(零开销)CAS设置ThreadId失败到达安全点检查T1状态撤销偏向锁升级为轻量级锁升级为轻量级锁暂停T1并复制锁记录

3.3 偏向锁的撤销条件

public class BiasedLockRevocation {

private static final Object lock = new Object();

public static void main(String[] args) throws InterruptedException {

Thread.sleep(5000); // 等待偏向锁启动

// 场景1: 调用hashCode()导致偏向锁撤销

Object obj1 = new Object();

synchronized (obj1) {

System.out.println("调用hashCode前: " + ClassLayout.parseInstance(obj1).toPrintable());

obj1.hashCode(); // 这会撤销偏向锁!

System.out.println("调用hashCode后: " + ClassLayout.parseInstance(obj1).toPrintable());

}

// 场景2: 调用wait/notify导致偏向锁撤销

Object obj2 = new Object();

synchronized (obj2) {

System.out.println("\n调用wait前: " + ClassLayout.parseInstance(obj2).toPrintable());

obj2.wait(100); // wait会撤销偏向锁并升级为重量级锁

System.out.println("调用wait后: " + ClassLayout.parseInstance(obj2).toPrintable());

}

}

}

四、轻量级锁(Lightweight Locking): 自旋的智慧

4.1 核心机制

当偏向锁被撤销或JVM禁用偏向锁时,锁会升级为轻量级锁。轻量级锁的核心是CAS + 自旋:

public class LightweightLockingDemo {

private static final Object lock = new Object();

private static int counter = 0;

public static void main(String[] args) throws InterruptedException {

// 使用偏向锁延迟,让锁直接进入轻量级锁

Object lightweightLock = new Object();

Thread t1 = new Thread(() ->{

synchronized (lightweightLock) {

System.out.println("线程1获取锁(轻量级锁):");

System.out.println(ClassLayout.parseInstance(lightweightLock).toPrintable());

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

Thread t2 = new Thread(() ->{

synchronized (lightweightLock) {

System.out.println("线程2获取锁(轻量级锁竞争):");

System.out.println(ClassLayout.parseInstance(lightweightLock).toPrintable());

}

});

t1.start();

Thread.sleep(50); // 确保t1先获取锁

t2.start();

t1.join();

t2.join();

}

}

4.2 轻量级锁的获取与释放

其他线程对象Mark Word线程栈(Lock Record)当前线程其他线程对象Mark Word线程栈(Lock Record)当前线程#publish-mermaid-1784691747677-4{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;}}#publish-mermaid-1784691747677-4 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747677-4 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747677-4 .error-icon{fill:#552222;}#publish-mermaid-1784691747677-4 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747677-4 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747677-4 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747677-4 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747677-4 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747677-4 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747677-4 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747677-4 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747677-4 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747677-4 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747677-4 p{margin:0;}#publish-mermaid-1784691747677-4 .actor{stroke:#9370DB;fill:#ECECFF;stroke-width:1;}#publish-mermaid-1784691747677-4 rect.actor.outer-path[data-look="neo"]{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 rect.note[data-look="neo"]{stroke:#aaaa33;fill:#fff5ad;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 text.actor>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747677-4 .actor-line{stroke:#9370DB;}#publish-mermaid-1784691747677-4 .innerArc{stroke-width:1.5;stroke-dasharray:none;}#publish-mermaid-1784691747677-4 .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#publish-mermaid-1784691747677-4 .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#publish-mermaid-1784691747677-4 [id$="-arrowhead"] path{fill:#333;stroke:#333;}#publish-mermaid-1784691747677-4 .sequenceNumber{fill:white;}#publish-mermaid-1784691747677-4 [id$="-sequencenumber"]{fill:#333;}#publish-mermaid-1784691747677-4 [id$="-crosshead"] path{fill:#333;stroke:#333;}#publish-mermaid-1784691747677-4 .messageText{fill:#333;stroke:none;}#publish-mermaid-1784691747677-4 .labelBox{stroke:#9370DB;fill:#ECECFF;filter:none;}#publish-mermaid-1784691747677-4 .labelText,#publish-mermaid-1784691747677-4 .labelText>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747677-4 .loopText,#publish-mermaid-1784691747677-4 .loopText>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747677-4 .sectionTitle,#publish-mermaid-1784691747677-4 .sectionTitle>tspan{fill:black;stroke:none;}#publish-mermaid-1784691747677-4 .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:#9370DB;fill:#9370DB;}#publish-mermaid-1784691747677-4 .note{stroke:#aaaa33;fill:#fff5ad;}#publish-mermaid-1784691747677-4 .noteText,#publish-mermaid-1784691747677-4 .noteText>tspan{fill:black;stroke:none;font-weight:normal;}#publish-mermaid-1784691747677-4 .activation0{fill:#f4f4f4;stroke:#666;}#publish-mermaid-1784691747677-4 .activation1{fill:#f4f4f4;stroke:#666;}#publish-mermaid-1784691747677-4 .activation2{fill:#f4f4f4;stroke:#666;}#publish-mermaid-1784691747677-4 .actorPopupMenu{position:absolute;}#publish-mermaid-1784691747677-4 .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#publish-mermaid-1784691747677-4 .actor-man circle,#publish-mermaid-1784691747677-4 line{fill:#ECECFF;stroke-width:2px;}#publish-mermaid-1784691747677-4 g rect.rect{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));stroke:#9370DB;}#publish-mermaid-1784691747677-4 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747677-4 [data-look="neo"].node rect,#publish-mermaid-1784691747677-4 [data-look="neo"].cluster rect,#publish-mermaid-1784691747677-4 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747677-4 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747677-4 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747677-4 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747677-4 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747677-4 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}获取轻量级锁标志位00(轻量级锁)alt[自旋成功][自旋失败]alt[是(重入)][否(竞争)]alt[CAS成功][CAS失败]释放轻量级锁alt[CAS成功][CAS失败]创建Lock Record拷贝Mark Word到Lock Record(Displaced Mark Word)CAS替换为指向Lock Record的指针获取锁成功检查是否指向当前线程的Lock Record重入成功自旋等待CAS再次尝试膨胀为重量级锁CAS恢复Displaced Mark Word释放成功说明已膨胀,按重量级锁释放

五、重量级锁(Heavyweight Locking): 最后的防线

5.1 Monitor对象结构

重量级锁通过操作系统层面的Monitor实现,涉及内核态切换:

public class HeavyweightLockingDemo {

private static final Object lock = new Object();

public static void main(String[] args) {

// 创建多个线程制造激烈竞争,触发重量级锁

for (int i = 0; i < 5; i++) {

new Thread(() ->{

synchronized (lock) {

System.out.println(Thread.currentThread().getName() +

" 持有锁时Mark Word:");

System.out.println(ClassLayout.parseInstance(lock).toPrintable());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}, "Thread-" + i).start();

}

}

}

5.2 Monitor的内部结构

#publish-mermaid-1784691747727-5{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;}}#publish-mermaid-1784691747727-5 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747727-5 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747727-5 .error-icon{fill:#552222;}#publish-mermaid-1784691747727-5 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747727-5 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747727-5 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747727-5 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747727-5 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747727-5 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747727-5 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747727-5 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747727-5 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747727-5 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747727-5 p{margin:0;}#publish-mermaid-1784691747727-5 g.classGroup text{fill:#9370DB;stroke:none;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:10px;}#publish-mermaid-1784691747727-5 g.classGroup text .title{font-weight:bolder;}#publish-mermaid-1784691747727-5 .cluster-label text{fill:#333;}#publish-mermaid-1784691747727-5 .cluster-label span{color:#333;}#publish-mermaid-1784691747727-5 .cluster-label span p{background-color:transparent;}#publish-mermaid-1784691747727-5 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#publish-mermaid-1784691747727-5 .cluster text{fill:#333;}#publish-mermaid-1784691747727-5 .cluster span{color:#333;}#publish-mermaid-1784691747727-5 .nodeLabel,#publish-mermaid-1784691747727-5 .edgeLabel{color:#131300;}#publish-mermaid-1784691747727-5 .noteLabel .nodeLabel,#publish-mermaid-1784691747727-5 .noteLabel .edgeLabel{color:black;}#publish-mermaid-1784691747727-5 .edgeLabel .label rect{fill:#ECECFF;}#publish-mermaid-1784691747727-5 .label text{fill:#131300;}#publish-mermaid-1784691747727-5 .labelBkg{background:#ECECFF;}#publish-mermaid-1784691747727-5 .edgeLabel .label span{background:#ECECFF;}#publish-mermaid-1784691747727-5 .classTitle{font-weight:bolder;}#publish-mermaid-1784691747727-5 .node rect,#publish-mermaid-1784691747727-5 .node circle,#publish-mermaid-1784691747727-5 .node ellipse,#publish-mermaid-1784691747727-5 .node polygon,#publish-mermaid-1784691747727-5 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1;}#publish-mermaid-1784691747727-5 .divider{stroke:#9370DB;stroke-width:1;}#publish-mermaid-1784691747727-5 g.clickable{cursor:pointer;}#publish-mermaid-1784691747727-5 g.classGroup rect{fill:#ECECFF;stroke:#9370DB;}#publish-mermaid-1784691747727-5 g.classGroup line{stroke:#9370DB;stroke-width:1;}#publish-mermaid-1784691747727-5 .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#publish-mermaid-1784691747727-5 .classLabel .label{fill:#9370DB;font-size:10px;}#publish-mermaid-1784691747727-5 .relation{stroke:#333333;stroke-width:1;fill:none;}#publish-mermaid-1784691747727-5 .dashed-line{stroke-dasharray:3;}#publish-mermaid-1784691747727-5 .dotted-line{stroke-dasharray:1 2;}#publish-mermaid-1784691747727-5 [id$="-compositionStart"],#publish-mermaid-1784691747727-5 .composition{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-compositionEnd"],#publish-mermaid-1784691747727-5 .composition{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-dependencyStart"],#publish-mermaid-1784691747727-5 .dependency{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-dependencyEnd"],#publish-mermaid-1784691747727-5 .dependency{fill:#333333!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-extensionStart"],#publish-mermaid-1784691747727-5 .extension{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-extensionEnd"],#publish-mermaid-1784691747727-5 .extension{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-aggregationStart"],#publish-mermaid-1784691747727-5 .aggregation{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-aggregationEnd"],#publish-mermaid-1784691747727-5 .aggregation{fill:transparent!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-lollipopStart"],#publish-mermaid-1784691747727-5 .lollipop{fill:#ECECFF!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 [id$="-lollipopEnd"],#publish-mermaid-1784691747727-5 .lollipop{fill:#ECECFF!important;stroke:#333333!important;stroke-width:1;}#publish-mermaid-1784691747727-5 .edgeTerminals{font-size:11px;line-height:initial;}#publish-mermaid-1784691747727-5 .classTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1784691747727-5 .edgeLabel[data-look="neo"]{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747727-5 .edgeLabel[data-look="neo"] p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747727-5 .edgeLabel[data-look="neo"] rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747727-5 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#publish-mermaid-1784691747727-5 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#publish-mermaid-1784691747727-5 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747727-5 [data-look="neo"].node rect,#publish-mermaid-1784691747727-5 [data-look="neo"].cluster rect,#publish-mermaid-1784691747727-5 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747727-5 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747727-5 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747727-5 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747727-5 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747727-5 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747727-5 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747727-5 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747727-5 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747727-5 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}ObjectMonitor-ObjectHeader header-int count-int waiters-Object owner-ObjectList entryList-ObjectList waitSet«Queue»EntryList竞争队列阻塞的线程«Queue»WaitSet等待队列wait() : 的线程«Thread»Owner持有锁的线程

六、锁升级的触发条件与JVM参数

6.1 锁升级触发条件总结

| 当前状态 | 升级条件 | 目标状态 | 升级成本 |

|---------|---------|---------|---------|

| 无锁 | 首次被线程获取 | 偏向锁 | 低(CAS设置ThreadID) |

| 偏向锁 | 另一线程竞争 | 轻量级锁 | 中等(需安全点+撤销) |

| 轻量级锁 | 自旋失败/竞争激烈 | 重量级锁 | 高(内核态切换) |

| 重量级锁 | 无法降级 | 重量级锁 | - |

6.2 关键JVM参数

/**

* 锁升级相关JVM参数配置

*/

public class JVMArgsForLockOptimization {

// 偏向锁参数

// -XX:+UseBiasedLocking 启用偏向锁(JDK 6-14默认开启, JDK 15+已废弃)

// -XX:BiasedLockingStartupDelay=0 偏向锁启动延迟(默认4000ms)

// -XX:-UseBiasedLocking 禁用偏向锁

// 轻量级锁参数

// -XX:PreBlockSpin=10 自旋次数(JDK 1.6默认10次)

// -XX:+UseSpinning 启用自旋锁(JDK 1.6+默认开启)

// 重量级锁参数

// -XX:+UseHeavyMonitors 强制使用重量级锁

public static void main(String[] args) {

System.out.println("Current JVM lock optimization settings:");

System.out.println("BiasedLocking: " + checkBiasedLocking());

}

private static String checkBiasedLocking() {

// 检查偏向锁是否启用

Object obj = new Object();

synchronized (obj) {

String markWord = Integer.toBinaryString(

obj.hashCode() & 0xFF

);

return markWord;

}

}

}

七、实战: 模拟锁升级全过程

7.1 完整的锁升级演示

public class LockUpgradeFullDemo {

private static final Object LOCK = new Object();

public static void main(String[] args) throws InterruptedException {

// 准备JOL依赖来观察Mark Word

// Maven: org.openjdk.jol:jol-core:0.16

// 阶段1: 无锁状态

System.out.println("========== 阶段1: 无锁状态 ==========");

printMarkWord("初始状态");

// 阶段2: 偏向锁

System.out.println("\n========== 阶段2: 偏向锁 ==========");

new Thread(() ->{

synchronized (LOCK) {

printMarkWord("线程1首次获取锁(偏向锁)");

}

}, "Thread-1").start();

Thread.sleep(100);

// 同一线程再次获取,依然是偏向锁

new Thread(() ->{

synchronized (LOCK) {

printMarkWord("线程1再次获取锁(仍是偏向锁)");

}

}, "Thread-1").start();

Thread.sleep(100);

// 阶段3: 轻量级锁(轻微竞争)

System.out.println("\n========== 阶段3: 轻量级锁 ==========");

Thread t2 = new Thread(() ->{

synchronized (LOCK) {

printMarkWord("线程2获取锁(偏向锁撤销->轻量级锁)");

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}, "Thread-2");

Thread t3 = new Thread(() ->{

synchronized (LOCK) {

printMarkWord("线程3获取锁(轻量级锁竞争)");

}

}, "Thread-3");

t2.start();

Thread.sleep(50);

t3.start();

t2.join();

t3.join();

// 阶段4: 重量级锁(激烈竞争)

System.out.println("\n========== 阶段4: 重量级锁 ==========");

for (int i = 0; i < 5; i++) {

final int id = i;

new Thread(() ->{

synchronized (LOCK) {

printMarkWord("线程" + id + "持有锁(激烈竞争)");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}, "Heavy-" + id).start();

}

Thread.sleep(2000);

printMarkWord("竞争结束后");

}

private static void printMarkWord(String message) {

System.out.println("[" + Thread.currentThread().getName() + "] " + message + ":");

System.out.println(ClassLayout.parseInstance(LOCK).toPrintable());

}

}

7.2 锁升级的性能对比

public class LockPerformanceComparison {

private static final int ITERATIONS = 10_000_000;

// 测试无竞争场景

public static void testNoContention() {

Object lock = new Object();

long start = System.nanoTime();

for (int i = 0; i < ITERATIONS; i++) {

synchronized (lock) {

// 空操作

}

}

long end = System.nanoTime();

System.out.println("无竞争场景(偏向锁): " +

(end - start) / 1_000_000 + "ms");

}

// 测试轻微竞争场景

public static void testLightContention() throws InterruptedException {

Object lock = new Object();

CountDownLatch latch = new CountDownLatch(2);

long start = System.nanoTime();

new Thread(() ->{

for (int i = 0; i < ITERATIONS / 2; i++) {

synchronized (lock) {

// 短暂持有锁

}

}

latch.countDown();

}).start();

new Thread(() ->{

for (int i = 0; i < ITERATIONS / 2; i++) {

synchronized (lock) {

// 短暂持有锁

}

}

latch.countDown();

}).start();

latch.await();

long end = System.nanoTime();

System.out.println("轻微竞争场景(轻量级锁): " +

(end - start) / 1_000_000 + "ms");

}

// 测试激烈竞争场景

public static void testHeavyContention() throws InterruptedException {

Object lock = new Object();

int threadCount = 10;

CountDownLatch latch = new CountDownLatch(threadCount);

long start = System.nanoTime();

for (int t = 0; t < threadCount; t++) {

new Thread(() ->{

for (int i = 0; i < ITERATIONS / threadCount; i++) {

synchronized (lock) {

// 短暂持有锁

}

}

latch.countDown();

}).start();

}

latch.await();

long end = System.nanoTime();

System.out.println("激烈竞争场景(重量级锁): " +

(end - start) / 1_000_000 + "ms");

}

public static void main(String[] args) throws InterruptedException {

System.out.println("=== 锁性能对比 (迭代次数: " + ITERATIONS + ") ===\n");

testNoContention();

testLightContention();

testHeavyContention();

}

}

八、JVM到底在优化什么: 核心思想总结

8.1 三种锁的本质对比

#publish-mermaid-1784691747822-6{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;}}#publish-mermaid-1784691747822-6 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747822-6 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747822-6 .error-icon{fill:#552222;}#publish-mermaid-1784691747822-6 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747822-6 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747822-6 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747822-6 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747822-6 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747822-6 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747822-6 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747822-6 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747822-6 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747822-6 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747822-6 p{margin:0;}#publish-mermaid-1784691747822-6 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#publish-mermaid-1784691747822-6 .cluster-label text{fill:#333;}#publish-mermaid-1784691747822-6 .cluster-label span{color:#333;}#publish-mermaid-1784691747822-6 .cluster-label span p{background-color:transparent;}#publish-mermaid-1784691747822-6 .label text,#publish-mermaid-1784691747822-6 span{fill:#333;color:#333;}#publish-mermaid-1784691747822-6 .node rect,#publish-mermaid-1784691747822-6 .node circle,#publish-mermaid-1784691747822-6 .node ellipse,#publish-mermaid-1784691747822-6 .node polygon,#publish-mermaid-1784691747822-6 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747822-6 .rough-node .label text,#publish-mermaid-1784691747822-6 .node .label text,#publish-mermaid-1784691747822-6 .image-shape .label,#publish-mermaid-1784691747822-6 .icon-shape .label{text-anchor:middle;}#publish-mermaid-1784691747822-6 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#publish-mermaid-1784691747822-6 .rough-node .label,#publish-mermaid-1784691747822-6 .node .label,#publish-mermaid-1784691747822-6 .image-shape .label,#publish-mermaid-1784691747822-6 .icon-shape .label{text-align:center;}#publish-mermaid-1784691747822-6 .node.clickable{cursor:pointer;}#publish-mermaid-1784691747822-6 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#publish-mermaid-1784691747822-6 .arrowheadPath{fill:#333333;}#publish-mermaid-1784691747822-6 .edgePath .path{stroke:#333333;stroke-width:1px;}#publish-mermaid-1784691747822-6 .flowchart-link{stroke:#333333;fill:none;}#publish-mermaid-1784691747822-6 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747822-6 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747822-6 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747822-6 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#publish-mermaid-1784691747822-6 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#publish-mermaid-1784691747822-6 .cluster text{fill:#333;}#publish-mermaid-1784691747822-6 .cluster span{color:#333;}#publish-mermaid-1784691747822-6 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;}#publish-mermaid-1784691747822-6 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1784691747822-6 rect.text{fill:none;stroke-width:0;}#publish-mermaid-1784691747822-6 .icon-shape,#publish-mermaid-1784691747822-6 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1784691747822-6 .icon-shape p,#publish-mermaid-1784691747822-6 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#publish-mermaid-1784691747822-6 .icon-shape .label rect,#publish-mermaid-1784691747822-6 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1784691747822-6 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#publish-mermaid-1784691747822-6 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#publish-mermaid-1784691747822-6 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747822-6 [data-look="neo"].node rect,#publish-mermaid-1784691747822-6 [data-look="neo"].cluster rect,#publish-mermaid-1784691747822-6 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747822-6 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747822-6 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747822-6 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747822-6 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747822-6 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747822-6 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747822-6 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747822-6 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747822-6 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}重量级锁 - 处理激烈竞争轻量级锁 - 优化线程交替执行偏向锁 - 优化单线程重复获取场景: 同一线程多次获取开销: 仅需检查ThreadID实现: CAS设置Mark Word代价: 最低场景: 多线程交替获取开销: CAS + 自旋实现: Lock Record栈帧代价: 中等场景: 多线程同时竞争开销: 用户态↔内核态切换实现: OS Mutex Lock代价: 最高

8.2 优化思想: 分层递进

JVM的锁升级机制体现了分层优化的经典设计思想: 拼多多帮助力入口

乐观假设: 大部分锁在多数时间都不存在竞争渐进升级: 只在必要时才升级到更重的锁不可逆: 锁只能升级不能降级(JDK 15之前)自适应: 根据运行时反馈动态调整

/**

* 锁优化的核心思想代码体现

*/

public class LockOptimizationPrinciple {

// JVM的优化思想可以抽象为以下伪代码

public void acquireLock(Object lock) {

// 第一层: 尝试偏向锁

if (isBiasedToCurrentThread(lock)) {

// 零开销, 直接进入临界区

return;

}

// 第二层: 尝试轻量级锁

if (tryLightweightLock(lock)) {

// CAS + 自适应自旋

return;

}

// 第三层: 膨胀为重量级锁

inflateToHeavyweightLock(lock);

}

private boolean isBiasedToCurrentThread(Object lock) {

// 检查Mark Word中的ThreadID

return false;

}

private boolean tryLightweightLock(Object lock) {

// CAS操作 + 自旋等待

return false;

}

private void inflateToHeavyweightLock(Object lock) {

// 创建Monitor对象, 进入阻塞队列

}

}

九、现代JVM的锁优化趋势

9.1 JDK 15: 偏向锁被废弃

/**

* JDK 15取消了偏向锁的默认启用

* 原因:

* 1. 现代应用多使用线程池,线程ID不固定

* 2. 偏向锁撤销需要在安全点执行,延迟高

* 3. 维护成本大于收益

*/

public class BiasedLockingDeprecation {

public static void main(String[] args) {

// JDK 15+ 输出偏向锁状态

System.out.println("JDK Version: " + System.getProperty("java.version"));

Object lock = new Object();

synchronized (lock) {

System.out.println(ClassLayout.parseInstance(lock).toPrintable());

// JDK 15+通常直接显示轻量级锁(00)

}

}

}

9.2 未来趋势

#publish-mermaid-1784691747897-7{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;}}#publish-mermaid-1784691747897-7 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747897-7 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1784691747897-7 .error-icon{fill:#552222;}#publish-mermaid-1784691747897-7 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1784691747897-7 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1784691747897-7 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1784691747897-7 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1784691747897-7 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1784691747897-7 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1784691747897-7 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1784691747897-7 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1784691747897-7 .marker.cross{stroke:#333333;}#publish-mermaid-1784691747897-7 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1784691747897-7 p{margin:0;}#publish-mermaid-1784691747897-7 .edge{stroke-width:3;}#publish-mermaid-1784691747897-7 .section--1 rect,#publish-mermaid-1784691747897-7 .section--1 path,#publish-mermaid-1784691747897-7 .section--1 circle,#publish-mermaid-1784691747897-7 .section--1 path{fill:hsl(240, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section--1 text{fill:#ffffff;}#publish-mermaid-1784691747897-7 .node-icon--1{font-size:40px;color:#ffffff;}#publish-mermaid-1784691747897-7 .section-edge--1{stroke:hsl(240, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth--1{stroke-width:17;}#publish-mermaid-1784691747897-7 .section--1 line{stroke:hsl(60, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:#ffffff;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-0 rect,#publish-mermaid-1784691747897-7 .section-0 path,#publish-mermaid-1784691747897-7 .section-0 circle,#publish-mermaid-1784691747897-7 .section-0 path{fill:hsl(60, 100%, 73.5294117647%);}#publish-mermaid-1784691747897-7 .section-0 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-0{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-0{stroke:hsl(60, 100%, 73.5294117647%);}#publish-mermaid-1784691747897-7 .edge-depth-0{stroke-width:14;}#publish-mermaid-1784691747897-7 .section-0 line{stroke:hsl(240, 100%, 83.5294117647%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-1 rect,#publish-mermaid-1784691747897-7 .section-1 path,#publish-mermaid-1784691747897-7 .section-1 circle,#publish-mermaid-1784691747897-7 .section-1 path{fill:hsl(80, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-1 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-1{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-1{stroke:hsl(80, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-1{stroke-width:11;}#publish-mermaid-1784691747897-7 .section-1 line{stroke:hsl(260, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-2 rect,#publish-mermaid-1784691747897-7 .section-2 path,#publish-mermaid-1784691747897-7 .section-2 circle,#publish-mermaid-1784691747897-7 .section-2 path{fill:hsl(270, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-2 text{fill:#ffffff;}#publish-mermaid-1784691747897-7 .node-icon-2{font-size:40px;color:#ffffff;}#publish-mermaid-1784691747897-7 .section-edge-2{stroke:hsl(270, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-2{stroke-width:8;}#publish-mermaid-1784691747897-7 .section-2 line{stroke:hsl(90, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:#ffffff;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-3 rect,#publish-mermaid-1784691747897-7 .section-3 path,#publish-mermaid-1784691747897-7 .section-3 circle,#publish-mermaid-1784691747897-7 .section-3 path{fill:hsl(300, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-3 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-3{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-3{stroke:hsl(300, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-3{stroke-width:5;}#publish-mermaid-1784691747897-7 .section-3 line{stroke:hsl(120, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-4 rect,#publish-mermaid-1784691747897-7 .section-4 path,#publish-mermaid-1784691747897-7 .section-4 circle,#publish-mermaid-1784691747897-7 .section-4 path{fill:hsl(330, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-4 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-4{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-4{stroke:hsl(330, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-4{stroke-width:2;}#publish-mermaid-1784691747897-7 .section-4 line{stroke:hsl(150, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-5 rect,#publish-mermaid-1784691747897-7 .section-5 path,#publish-mermaid-1784691747897-7 .section-5 circle,#publish-mermaid-1784691747897-7 .section-5 path{fill:hsl(0, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-5 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-5{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-5{stroke:hsl(0, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-5{stroke-width:-1;}#publish-mermaid-1784691747897-7 .section-5 line{stroke:hsl(180, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-6 rect,#publish-mermaid-1784691747897-7 .section-6 path,#publish-mermaid-1784691747897-7 .section-6 circle,#publish-mermaid-1784691747897-7 .section-6 path{fill:hsl(30, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-6 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-6{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-6{stroke:hsl(30, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-6{stroke-width:-4;}#publish-mermaid-1784691747897-7 .section-6 line{stroke:hsl(210, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-7 rect,#publish-mermaid-1784691747897-7 .section-7 path,#publish-mermaid-1784691747897-7 .section-7 circle,#publish-mermaid-1784691747897-7 .section-7 path{fill:hsl(90, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-7 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-7{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-7{stroke:hsl(90, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-7{stroke-width:-7;}#publish-mermaid-1784691747897-7 .section-7 line{stroke:hsl(270, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-8 rect,#publish-mermaid-1784691747897-7 .section-8 path,#publish-mermaid-1784691747897-7 .section-8 circle,#publish-mermaid-1784691747897-7 .section-8 path{fill:hsl(150, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-8 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-8{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-8{stroke:hsl(150, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-8{stroke-width:-10;}#publish-mermaid-1784691747897-7 .section-8 line{stroke:hsl(330, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-9 rect,#publish-mermaid-1784691747897-7 .section-9 path,#publish-mermaid-1784691747897-7 .section-9 circle,#publish-mermaid-1784691747897-7 .section-9 path{fill:hsl(180, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-9 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-9{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-9{stroke:hsl(180, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-9{stroke-width:-13;}#publish-mermaid-1784691747897-7 .section-9 line{stroke:hsl(0, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-10 rect,#publish-mermaid-1784691747897-7 .section-10 path,#publish-mermaid-1784691747897-7 .section-10 circle,#publish-mermaid-1784691747897-7 .section-10 path{fill:hsl(210, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .section-10 text{fill:black;}#publish-mermaid-1784691747897-7 .node-icon-10{font-size:40px;color:black;}#publish-mermaid-1784691747897-7 .section-edge-10{stroke:hsl(210, 100%, 76.2745098039%);}#publish-mermaid-1784691747897-7 .edge-depth-10{stroke-width:-16;}#publish-mermaid-1784691747897-7 .section-10 line{stroke:hsl(30, 100%, 86.2745098039%);stroke-width:3;}#publish-mermaid-1784691747897-7 .lineWrapper line{stroke:black;}#publish-mermaid-1784691747897-7 .disabled,#publish-mermaid-1784691747897-7 .disabled circle,#publish-mermaid-1784691747897-7 .disabled text{fill:hsl(80, 100%, 96.2745098039%);}#publish-mermaid-1784691747897-7 .disabled text{fill:#aaaa33;}#publish-mermaid-1784691747897-7 .section-root rect,#publish-mermaid-1784691747897-7 .section-root path,#publish-mermaid-1784691747897-7 .section-root circle{fill:hsl(240, 100%, 46.2745098039%);}#publish-mermaid-1784691747897-7 .section-root text{fill:#ffffff;}#publish-mermaid-1784691747897-7 .icon-container{height:100%;display:flex;justify-content:center;align-items:center;}#publish-mermaid-1784691747897-7 .edge{fill:none;}#publish-mermaid-1784691747897-7 .eventWrapper{filter:brightness(120%);}#publish-mermaid-1784691747897-7 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1784691747897-7 [data-look="neo"].node rect,#publish-mermaid-1784691747897-7 [data-look="neo"].cluster rect,#publish-mermaid-1784691747897-7 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747897-7 [data-look="neo"].swimlane.cluster rect{filter:none;}#publish-mermaid-1784691747897-7 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1784691747897-7 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747897-7 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1784691747897-7 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747897-7 [data-look="neo"].node circle .state-start{fill:#000000;}#publish-mermaid-1784691747897-7 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747897-7 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1784691747897-7 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}JDK 1.0重量级锁(synchronized原生实现)JDK 1.6偏向锁 +轻量级锁

自适应自旋

锁消除/锁粗化JDK 1.8优化偏向锁撤销

ThreadLocal BufferJDK 15废弃偏向锁

默认禁用Loom项目VirtualThread与synchronized

可能重新设计锁机制JVM锁优化演进路线

十、总结与最佳实践

10.1 核心要点

锁升级路径: 无锁 ->偏向锁 ->轻量级锁 ->重量级锁不可逆性: 锁只能升级,不能降级JVM优化目标: 在保证线程安全的前提下,尽量减少锁操作的开销自适应策略: JVM根据竞争情况自动选择最优锁状态

10.2 开发建议

/**

* 锁使用最佳实践

*/

public class LockBestPractices {

// 1. 减少锁持有时间

public void goodPractice() {

String data = prepareData(); // 锁外准备数据

synchronized (this) {

// 只在临界区做必要操作

updateSharedState(data);

}

processResult(); // 锁外处理结果

}

// 2. 降低锁粒度

private final Object lock1 = new Object();

private final Object lock2 = new Object();

public void fineGrainedLocking() {

synchronized (lock1) {

// 操作资源1

}

synchronized (lock2) {

// 操作资源2

}

}

// 3. 使用并发工具类替代synchronized

private final ConcurrentHashMapmap =

new ConcurrentHashMap<>();

private String prepareData() { return "data"; }

private void updateSharedState(String data) {}

private void processResult() {}

}

10.3 选择建议总结表

| 场景 | 建议方案 | 原因 |

|------|---------|------|

| 单线程重复获取 | JDK 15+直接用synchronized | 轻量级锁已足够高效 |

| 多线程交替执行 | synchronized + 轻量级锁 | 自旋避免内核切换 |

| 激烈竞争 | ReentrantLock或优化业务 | 减少锁竞争是根本 |

| 读多写少 | ReadWriteLock/StampedLock | 允许多个读并发 |

| 极高并发 | Lock-free数据结构 | 避免任何形式的锁 |

理解synchronized的锁升级机制,不仅能写出更高效的并发代码,也能在面试中展示对JVM底层原理的深刻理解。JVM团队用二十多年的时间证明了: 简单并不意味着低效,关键看实现。

---

如果本文帮你理解了锁升级的奥秘,欢迎点赞收藏。如有疑问,欢迎评论区交流!

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧