深入拆解 JVM 运行时内存区域:HotSpot 架构全景与动态执行模拟器
在学习 Java 虚拟机的过程中,运行时数据区(Runtime Data Area) 和 字节码执行引擎(Bytecode Execution Engine) 是最基础也是最核心的知识体系。然而,书本上抽象的文字描述(如“操作数栈作为临时工作台”、“局部变量表按 Slot 寻址”、“字符串常量池驻留引用”、“Cleaner 虚引用回收堆外内存”)往往难以在大脑中形成立体直观的模型。
为了彻底看清 JVM 在执行 Java 代码时,内部的程序计数器、虚拟机栈、操作数栈、Java 堆、元空间(Metaspace)、本地方法栈以及堆外直接内存是如何协同工作的,我们构建了一个基于 HotSpot 架构的动态单步执行模拟器。
你可以直接在下方进行交互操作:支持单步前进/后退、自动演示、调节播放速度,以及鼠标悬停内存地址高亮追踪引用关系!
交互式模拟器:JVM 运行时内存区域全景
💡 交互提示:
- 点击 “自动演示” 或 “下一步”,逐步追踪代码执行对应的内存变化;
- 将鼠标悬浮在任意内存地址(如
0x1A2B、0x9F00、0xFF88)上,系统将高亮显示该地址在栈帧局部变量表、操作数栈、堆对象以及堆外内存中的完整引用链路;- 点击控制栏右侧的放大按钮,或点击下方的全屏链接,即可进入沉浸式全屏视图。
演示源码与字节码指令集
模拟器中所运行的 Java 测试代码如下:
public class JvmDemo {
private static final int BASE = 10;
public static void main(String[] args) {
int x = 5;
User user = new User("Alice", x);
int res = user.calc(BASE);
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
} // main 结束,栈帧弹出,触发 GC 可达性分析
}
class User {
String name;
int age;
public User(String n, int a) {
this.name = n;
this.age = a;
}
public int calc(int base) {
return this.age + base;
}
}使用 javap -c -v JvmDemo 反编译得到的核心字节码序列如下:
public static void main(java.lang.String[]);
Code:
stack=4, locals=5, args_size=1
0: iconst_5 // 常量 5 压入操作数栈
1: istore_1 // 弹出 5 存入局部变量表 Slot 1 (x)
2: new #2 // class User // 在堆中为 User 分配内存并压入引用
5: dup // 复制栈顶引用(一份用于 invokespecial,一份留给 astore)
6: ldc #3 // String Alice // 常量池加载 "Alice" 引用压栈
8: iload_1 // 加载局部变量 x (5) 压栈
9: invokespecial #4 // Method User."<init>":(Ljava/lang/String;I)V // 调用构造方法
12: astore_2 // 弹出 User 引用存入局部变量表 Slot 2 (user)
13: aload_2 // 加载 user 引用压栈
14: bipush 10 // 常量折叠加载 BASE=10 压栈
16: invokevirtual #5 // Method User.calc:(I)I // 调用 calc() 方法
19: istore_3 // 将返回值 15 存入局部变量表 Slot 3 (res)
20: sipush 1024 // 压入容量 1024
23: invokestatic #7 // Method java/nio/ByteBuffer.allocateDirect:(I)
26: astore 4 // 存入局部变量表 Slot 4 (buf)
28: return // main 方法结束,栈帧出栈核心内存区域深度剖析
根据《Java 虚拟机规范》,JVM 运行时数据区通常划分为以下几个部分:
┌─────────────────────────────────────────────────────────────┐
│ Java 虚拟机运行时数据区 │
├──────────────────────────────┬──────────────────────────────┤
│ 线程私有区域 │ 线程共享区域 │
│ (生命周期与线程启动/销毁相同) │ (生命周期与 JVM 启动/停止相同) │
├──────────────────────────────┼──────────────────────────────┤
│ 1. 程序计数器 (PC Register) │ 1. Java 堆 (Heap) │
│ 2. Java 虚拟机栈 (JVM Stack) │ - 年轻代 (Eden/Survivor) │
│ 3. 本地方法栈 (Native Stack) │ - 老年代 (Tenured) │
│ │ - 字符串常量池 (String Pool)│
│ │ 2. 元空间 / 方法区 (Metaspace)│
│ │ - 类元数据 (Klass) │
│ │ - 运行时常量池 │
├──────────────────────────────┴──────────────────────────────┤
│ 堆外内存 / 直接内存 (Direct Memory) │
│ (OS 本地内存,NIO 零拷贝通道,由 Cleaner 虚引用管理) │
└─────────────────────────────────────────────────────────────┘1. 程序计数器(Program Counter Register)
- 本质与作用:记录当前线程正在执行的字节码指令地址(行号指示器)。在多线程并发执行时,CPU 会在不同线程之间来回切换时间片,恢复调度时需要依靠 PC 寄存器知道从哪一条指令继续执行。
- 内存特性:线程私有,占用极小内存,并且是 JVM 规范中唯一一个没有任何
OutOfMemoryError(OOM)情况的内存区域。
2. Java 虚拟机栈与栈帧(JVM Stack & Stack Frames)
每个 Java 方法从调用到执行结束,都对应着一个**栈帧(Stack Frame)**在虚拟机栈中从入栈到出栈的过程。栈帧包含四个核心要素:
- 局部变量表(Local Variable Table):
- 存储方法参数和方法体内部定义的局部变量。
- 存储单元是 Slot(变量槽)。在实例方法中,Slot 0 默认是隐式参数
this;在static main(String[] args)中,Slot 0 存放命令行参数数组args。 boolean, byte, char, short, int, float, reference占用 1 个 Slot,而long, double占用连续的 2 个 Slot。
- 操作数栈(Operand Stack):
- JVM 是一台基于栈式架构的虚拟机(与基于寄存器架构的 Dalvik/x86 不同)。所有加减乘除、对象创建入参、方法调用入参,都必须经过操作数栈进行压栈(Push)和出栈(Pop)计算。
- 动态链接(Dynamic Linking):
- 每个栈帧内部包含一个指向运行时常量池中该方法的符号引用。在每次方法运行期间,将符号引用解析为直接内存入口地址(支持多态分派)。
- 方法返回地址(Return Address):
- 记录调用方方法在调用此方法后的下一条 PC 指令地址(例如
main @ 0x0014),方法正常执行完毕(ireturn、return)后,恢复调用者的 PC 计数器并传递返回值。
- 记录调用方方法在调用此方法后的下一条 PC 指令地址(例如
3. Java 堆(Heap)与对象内存布局
在 HotSpot 虚拟机中,Java 堆是垃圾收集器管理的最大一块区域。当执行 new User("Alice", 5) 时:
- 分配检查与内存划定:先检查元空间中
User.class是否已完成类加载。接着在堆(Eden 区)划分出对应大小的内存块(如指针碰撞 Bump the Pointer 或 TLAB 线程本地分配缓冲)。 - 对象内存结构:
- 对象头(Object Header):
- Mark Word:包含 HashCode、GC 分代年龄、锁状态标识(无锁/偏向锁/轻量级锁/重量级锁)、偏向线程 ID。
- Klass Pointer(类型指针):指向元空间中的类元数据(Klass),确定该对象是哪个类的实例。
- 实例数据(Instance Data):各个字段的具体数值或引用指针(如
name: 0x9F00,age: 5)。 - 对齐填充(Padding):保证对象总字节数是 8 字节的整数倍。
- 对象头(Object Header):
4. 字符串常量池(String Pool)
- 在 JDK 7 之后,字符串常量池从永久代移入了 Java 堆中。
- 当字节码执行
ldc "Alice"时,JVM 会在内部的StringTable(散列表结构)中查找是否存在"Alice"。若首次出现,则在堆中构造 String 对象实例(如模拟器中的0x9F00),并将该对象的引用保存在 StringTable 中供复用。
5. 堆外直接内存(Off-Heap Direct Memory)与 Cleaner 虚引用
- 当调用
ByteBuffer.allocateDirect(1024)时,JVM 通过 JNI(Java Native Interface)调用底层 C 语言标准库malloc(1024),直接在操作系统的本地物理内存中分配缓冲区(地址0xFF88)。 - 优势:减少了一次从 Java 堆复制到操作系统的“中间缓冲拷贝”(Zero-Copy 零拷贝),大幅提升网络 I/O 与文件读写吞吐量。
- 回收机制:堆内分配的
DirectByteBuffer对象(地址0x7C00)仅仅是一个包装壳,内部关联了一个Cleaner虚引用(PhantomReference)。当DirectByteBuffer变为不可达被 Young GC 回收时,Cleaner 会被加入 ReferenceQueue,由后台线程调用Unsafe.freeMemory(0xFF88)将物理内存释放回操作系统。
模拟器 14 步执行时序对照表
| 步骤 | 阶段 | 核心字节码 / 行为 | 内存变化说明 |
|---|---|---|---|
| #1 | 类加载期 | ClassLoader.loadClass | JvmDemo.class 载入元空间,静态常量 BASE=10 写入常量池 |
| #2 | 栈帧创建 | main() 入栈 | 创建 main 栈帧,初始化局部变量表 Slot[0] = args |
| #3 | 操作数栈 | iconst_5 | 常数 5 压入 main 栈帧的操作数栈顶 |
| #4 | 局部变量表 | istore_1 | 弹出栈顶 5,写入局部变量表 Slot[1](变量 x) |
| #5 | 堆分配 | new #2 <User> | 在 Eden 区分配内存 0x1A2B,赋默认初值,引用压栈 |
| #6 | 常量池引用 | ldc "Alice" & iload_1 | 堆中 String Pool 创建 "Alice"(0x9F00),将引用与 x(5) 压入操作数栈 |
| #7 | 构造器调用 | invokespecial <init> | User.<init> 栈帧入栈,接收 this(0x1A2B), n, a 并修改堆字段 |
| #8 | 栈帧出栈 | astore_2 | <init> 栈帧销毁,main 将引用 0x1A2B 赋给局部变量 user(Slot[2]) |
| #9 | 方法调用 | invokevirtual <calc> | 动态链接解析虚方法表,User.calc 栈帧入栈 |
| #10 | 字段读取 | getfield #6 & iload_1 | 通过 this 去堆中读取 age=5 压栈,加载参数 base=10 压栈 |
| #11 | 算术运算 | iadd | 弹出 10 和 5,执行 CPU 加法,结果 15 压回操作数栈顶 |
| #12 | 方法返回 | ireturn & istore_3 | calc 栈帧弹出,返回值 15 传回 main,存入 Slot[3](变量 res) |
| #13 | 直接内存 | allocateDirect(1024) | JNI 调用 malloc 分配堆外内存 0xFF88,堆内创建 DirectByteBuffer 壳 |
| #14 | GC 演示 | return & Young GC | main 退出,局部变量指针全部失效,GC Roots 清空;堆对象回收并触发 Cleaner 释放堆外内存 |
模拟器完整源码实现保存
这份模拟器采用 React 18 + Tailwind CSS 编写,纯前端驱动,无需任何服务端运行时。完整的前端组件源码已打包固化在博客工程的 public/jvm-memory-simulator.html 中,完整源码如下备份:
import React, { useState, useEffect, useMemo } from 'react';
import {
Play, Pause, SkipBack, SkipForward, RotateCcw,
Cpu, Layers, Database, HardDrive, Code2, Sparkles,
ArrowRight, Info, Zap, Trash2, Link2, Terminal, ChevronRight
} from 'lucide-react';
// ==========================================
// 1. 源码与字节码数据定义
// ==========================================
const JAVA_CODE_LINES = [
{ line: 1, code: 'public class JvmDemo {', indent: 0 },
{ line: 2, code: 'private static final int BASE = 10;', indent: 1 },
{ line: 3, code: 'public static void main(String[] args) {', indent: 1 },
{ line: 4, code: 'int x = 5;', indent: 2 },
{ line: 5, code: 'User user = new User("Alice", x);', indent: 2 },
{ line: 6, code: 'int res = user.calc(BASE);', indent: 2 },
{ line: 7, code: 'ByteBuffer buf = ByteBuffer.allocateDirect(1024);', indent: 2 },
{ line: 8, code: '} // main 结束,触发 GC 演示', indent: 1 },
{ line: 9, code: '}', indent: 0 },
{ line: 10, code: '', indent: 0 },
{ line: 11, code: 'class User {', indent: 0 },
{ line: 12, code: 'String name; int age;', indent: 1 },
{ line: 13, code: 'public User(String n, int a) {', indent: 1 },
{ line: 14, code: 'this.name = n; this.age = a;', indent: 2 },
{ line: 15, code: '}', indent: 1 },
{ line: 16, code: 'public int calc(int base) {', indent: 1 },
{ line: 17, code: 'return this.age + base;', indent: 2 },
{ line: 18, code: '}', indent: 1 },
{ line: 19, code: '}', indent: 0 },
];
// ==========================================
// 2. 14个核心精细步骤定义
// ==========================================
const EXECUTION_STEPS = [
{
id: 0,
title: '步骤 1:类加载与元空间初始化 (Class Loading)',
tag: '类加载期',
activeLines: [1, 2],
pc: '0x0000 (准备就绪)',
bytecode: 'clinit / ClassLoader.loadClass("JvmDemo")',
explanation: 'JVM 启动,通过类加载器将 JvmDemo.class 加载到【元空间(Metaspace)】。静态常量 BASE = 10 随类元信息一同存入元空间的运行时常量池中。此时尚未创建任何线程栈帧。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'calc(int)']
},
frames: [],
stringPool: [],
heapObjects: [],
directMemory: []
},
{
id: 1,
title: '步骤 2:main 方法栈帧入栈 (Stack Frame Push)',
tag: '栈帧创建',
activeLines: [3],
pc: '0x0000: main()',
bytecode: '// 创建 main 栈帧,初始化局部变量表 Slot[0]=args',
explanation: '主线程启动,在【Java 虚拟机栈】中压入 main() 方法栈帧。栈帧包含局部变量表(Slot 0 存放命令行参数 args 引用)、空的操作数栈、动态链接和返回地址。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000 (String[])', ref: null, highlight: true }
],
operandStack: []
}
],
stringPool: [],
heapObjects: [],
directMemory: []
},
{
id: 2,
title: '步骤 3:常量 5 压入操作数栈 (iconst_5)',
tag: '操作数栈',
activeLines: [4],
pc: '0x0001: iconst_5',
bytecode: '0x0001: iconst_5 // 将 int 型常量 5 压入操作数栈',
explanation: '执行 int x = 5 的第一步:JVM 基于栈架构,不能直接把数值写进局部变量表,必须先执行 iconst_5 指令,将常数 5 压入【操作数栈(Operand Stack)】栈顶。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null }
],
operandStack: [
{ value: '5', type: 'int', desc: '常量 5', highlight: true }
]
}
],
stringPool: [],
heapObjects: [],
directMemory: []
},
{
id: 3,
title: '步骤 4:弹出栈顶并存入局部变量表 (istore_1)',
tag: '局部变量表',
activeLines: [4],
pc: '0x0002: istore_1',
bytecode: '0x0002: istore_1 // 将栈顶 int 弹出,存入局部变量表 Slot 1 (x)',
explanation: '执行 istore_1 指令:将操作数栈顶的 5 弹出(Pop),写入 main 栈帧【局部变量表】的 Slot 1(即变量 x)。基本数据类型直接将具体数值保存在栈帧的槽位中。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null, highlight: true }
],
operandStack: []
}
],
stringPool: [],
heapObjects: [],
directMemory: []
},
{
id: 4,
title: '步骤 5:堆中分配 User 实例内存 (new #2 <User>)',
tag: '堆内存分配',
activeLines: [5, 11],
pc: '0x0003: new #2 <User>',
bytecode: '0x0003: new #2 <User>\n0x0006: dup',
explanation: '遇到 new User(...):首先检查 User 类是否加载(若未加载则载入元空间),随后在【Java 堆(Eden 区)】分配一块内存(地址 0x1A2B),此时属性为默认值(name=null, age=0),并将引用 0x1A2B 压入操作数栈。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class (新加载)'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null }
],
operandStack: [
{ value: '0x1A2B', type: 'ref', desc: 'User 引用 (未初始化)', ref: '0x1A2B', highlight: true }
]
}
],
stringPool: [],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: 'null', ref: null },
{ name: 'age', value: '0 (默认初值)', ref: null }
],
highlight: true
}
],
directMemory: []
},
{
id: 5,
title: '步骤 6:加载字符串字面量与参数入栈 (ldc "Alice" & iload_1)',
tag: '字符串常量池',
activeLines: [5],
pc: '0x0007: ldc #3 <"Alice">',
bytecode: '0x0007: ldc #3 <"Alice"> // 常量池加载字符串引用\n0x0009: iload_1 // 加载局部变量 x (5)',
explanation: '准备构造器参数:字面量 "Alice" 首次出现,JVM 在堆内的【字符串常量池(String Pool)】创建 "Alice" 对象(0x9F00),并将其引用与局部变量 x(5) 依次压入操作数栈。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null }
],
operandStack: [
{ value: '0x1A2B', type: 'ref', desc: 'User 引用', ref: '0x1A2B' },
{ value: '0x9F00', type: 'ref', desc: '"Alice" 引用', ref: '0x9F00', highlight: true },
{ value: '5', type: 'int', desc: '参数 x=5', highlight: true }
]
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"', highlight: true }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: 'null', ref: null },
{ name: 'age', value: '0', ref: null }
]
}
],
directMemory: []
},
{
id: 6,
title: '步骤 7:调用构造方法 User.<init> 栈帧入栈 (invokespecial)',
tag: '构造方法入栈',
activeLines: [5, 13, 14],
pc: '0x0010: putfield #4 <User.name>',
bytecode: '0x000A: invokespecial #4 <User.<init>>\n ↳ putfield User.name / putfield User.age',
explanation: '调用构造器:压入新的【User.<init> 栈帧】!原 main 操作数栈顶的参数被传递到新栈帧的局部变量表:Slot 0 存隐式参数 this(0x1A2B),Slot 1 存 n(0x9F00),Slot 2 存 a(5)。同时修改堆中 0x1A2B 对象的字段值。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null }
],
operandStack: [
{ value: '0x1A2B', type: 'ref', desc: 'User 引用', ref: '0x1A2B' }
]
},
{
id: 'init',
name: 'User.<init>(String, int)',
returnAddr: 'main @ 0x000D',
dynamicLink: 'User.<init> -> #SymRef_02',
highlight: true,
locals: [
{ slot: 0, name: 'this', value: '0x1A2B', ref: '0x1A2B', highlight: true },
{ slot: 1, name: 'n', value: '0x9F00 ("Alice")', ref: '0x9F00', highlight: true },
{ slot: 2, name: 'a', value: '5 (int)', ref: null, highlight: true }
],
operandStack: []
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00', highlight: true },
{ name: 'age', value: '5', ref: null, highlight: true }
],
highlight: true
}
],
directMemory: []
},
{
id: 7,
title: '步骤 8:构造方法出栈,引用赋值给局部变量 user (astore_2)',
tag: '栈帧弹出 & 引用赋值',
activeLines: [5, 15],
pc: '0x000D: astore_2',
bytecode: '0x000D: astore_2 // 将堆对象引用 0x1A2B 存入 Slot 2 (user)',
explanation: 'User.<init> 执行完毕,栈帧弹出(Pop)销毁!回到 main 栈帧,执行 astore_2 将操作数栈顶的引用地址 0x1A2B 存入局部变量表 Slot 2(user)。注意:栈上只存了 0x1A2B 这个指针,对象实体在堆里!',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null },
{ slot: 2, name: 'user', value: '0x1A2B (ref)', ref: '0x1A2B', highlight: true }
],
operandStack: []
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00' },
{ name: 'age', value: '5', ref: null }
]
}
],
directMemory: []
},
{
id: 8,
title: '步骤 9:调用 user.calc(BASE) 压入新栈帧 (invokevirtual)',
tag: '动态链接 & 入栈',
activeLines: [6, 16],
pc: '0x0012: invokevirtual #5 <User.calc>',
bytecode: '0x000E: aload_2 // 加载 user 引用 (0x1A2B)\n0x000F: bipush 10 // 常量折叠加载 BASE=10\n0x0011: invokevirtual #5 <User.calc>',
explanation: '调用成员方法 user.calc(BASE):通过栈帧中的【动态链接】在运行时常量池找到 User.calc 的符号引用并解析为直接地址,压入新的【User.calc 栈帧】。Slot 0 为 this(0x1A2B),Slot 1 为参数 base(10)。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null },
{ slot: 2, name: 'user', value: '0x1A2B (ref)', ref: '0x1A2B' }
],
operandStack: []
},
{
id: 'calc',
name: 'User.calc(int base)',
returnAddr: 'main @ 0x0014',
dynamicLink: 'User.calc() -> #SymRef_05 (多态分派)',
highlight: true,
locals: [
{ slot: 0, name: 'this', value: '0x1A2B', ref: '0x1A2B', highlight: true },
{ slot: 1, name: 'base', value: '10 (int)', ref: null, highlight: true }
],
operandStack: []
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00' },
{ name: 'age', value: '5', ref: null }
]
}
],
directMemory: []
},
{
id: 9,
title: '步骤 10:calc 内部读取字段与参数压入操作数栈 (getfield & iload_1)',
tag: '操作数栈入栈',
activeLines: [17],
pc: '0x0020: getfield #6 <User.age>',
bytecode: '0x001F: aload_0 // 加载 this (0x1A2B)\n0x0020: getfield #6 <User.age> // 读取堆中 age=5 压栈\n0x0023: iload_1 // 加载局部变量 base=10 压栈',
explanation: '在 User.calc 栈帧中执行加法前准备:先通过 this(0x1A2B) 去堆中读取 age 字段的值(5)压入操作数栈,再把局部变量表 Slot 1 的 base(10)压入操作数栈。此时操作数栈中有两个待运算的整数:5 和 10。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null },
{ slot: 2, name: 'user', value: '0x1A2B (ref)', ref: '0x1A2B' }
],
operandStack: []
},
{
id: 'calc',
name: 'User.calc(int base)',
returnAddr: 'main @ 0x0014',
dynamicLink: 'User.calc() -> #SymRef_05',
locals: [
{ slot: 0, name: 'this', value: '0x1A2B', ref: '0x1A2B' },
{ slot: 1, name: 'base', value: '10 (int)', ref: null }
],
operandStack: [
{ value: '5', type: 'int', desc: 'this.age (来自堆 0x1A2B)', highlight: true },
{ value: '10', type: 'int', desc: '局部变量 base', highlight: true }
]
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00' },
{ name: 'age', value: '5', ref: null }
]
}
],
directMemory: []
},
{
id: 10,
title: '步骤 11:执行 iadd 字节码运算 (Operand Stack Add)',
tag: 'iadd 算术运算',
activeLines: [17],
pc: '0x0024: iadd',
bytecode: '0x0024: iadd // 弹出栈顶 10 和 5,计算 5+10=15 压回栈顶\n0x0025: ireturn // 准备将栈顶 15 返回给调用者',
explanation: '执行核心运算指令 iadd:CPU 从 User.calc 的【操作数栈】同时弹出 10 和 5,相加得到 15,再将结果 15 压回操作数栈顶!这就是“操作数栈作为临时计算工作台”的直观体现。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null },
{ slot: 2, name: 'user', value: '0x1A2B (ref)', ref: '0x1A2B' }
],
operandStack: []
},
{
id: 'calc',
name: 'User.calc(int base)',
returnAddr: 'main @ 0x0014',
dynamicLink: 'User.calc() -> #SymRef_05',
locals: [
{ slot: 0, name: 'this', value: '0x1A2B', ref: '0x1A2B' },
{ slot: 1, name: 'base', value: '10 (int)', ref: null }
],
operandStack: [
{ value: '15', type: 'int', desc: 'iadd 计算结果 (5 + 10)', highlight: true }
]
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00' },
{ name: 'age', value: '5', ref: null }
]
}
],
directMemory: []
},
{
id: 11,
title: '步骤 12:ireturn 方法返回,calc 栈帧出栈,结果存入 res',
tag: '方法返回 & 出栈',
activeLines: [6, 17],
pc: '0x0014: istore_3',
bytecode: '0x0025: ireturn // calc 栈帧弹出,返回值压入 main 操作数栈\n0x0014: istore_3 // 弹出 15 存入 main 局部变量表 Slot 3 (res)',
explanation: '执行 ireturn:根据栈帧中的【方法返回地址(main @ 0x0014)】,将返回值 15 推入调用者 main 的操作数栈,随后销毁 User.calc 栈帧,PC 计数器恢复到 main 的 0x0014 指令,将 15 存入 Slot 3(变量 res)。',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null },
{ slot: 2, name: 'user', value: '0x1A2B (ref)', ref: '0x1A2B' },
{ slot: 3, name: 'res', value: '15 (int)', ref: null, highlight: true }
],
operandStack: []
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00' },
{ name: 'age', value: '5', ref: null }
]
}
],
directMemory: []
},
{
id: 12,
title: '步骤 13:调用 Native 方法分配堆外直接内存 (allocateDirect)',
tag: 'Native 方法 & 直接内存',
activeLines: [7],
pc: '0x0018: invokestatic <ByteBuffer.allocateDirect>',
bytecode: '0x0015: sipush 1024\n0x0018: invokestatic #7 <ByteBuffer.allocateDirect>\n ↳ [JNI] Unsafe.allocateMemory0(1024) [Native C++]',
explanation: '执行 ByteBuffer.allocateDirect(1024):底层触发 native 方法 Unsafe.allocateMemory。此时线程激活【本地方法栈(Native Method Stack)】,通过 JNI 调用 C 库 malloc 在【堆外直接内存】分配 1024B 空间(地址 0xFF88),并在堆内创建 DirectByteBuffer 壳对象(0x7C00)关联该地址!',
nativeActive: {
method: 'Unsafe.allocateMemory0(1024L)',
lib: 'libjvm.dylib / malloc(1024)',
returnVal: '0xFF88 (Native Memory Address)'
},
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class', 'DirectByteBuffer.class'],
constants: [{ name: 'BASE', value: '10', type: 'static final int' }],
methods: ['main(String[])', 'ByteBuffer.allocateDirect(int)', 'Unsafe.allocateMemory(native)']
},
frames: [
{
id: 'main',
name: 'main(String[] args)',
returnAddr: 'JVM Exit',
dynamicLink: 'JvmDemo.main() -> #SymRef_01',
locals: [
{ slot: 0, name: 'args', value: '0x0000', ref: null },
{ slot: 1, name: 'x', value: '5 (int)', ref: null },
{ slot: 2, name: 'user', value: '0x1A2B (ref)', ref: '0x1A2B' },
{ slot: 3, name: 'res', value: '15 (int)', ref: null },
{ slot: 4, name: 'buf', value: '0x7C00 (ref)', ref: '0x7C00', highlight: true }
],
operandStack: []
}
],
stringPool: [
{ address: '0x9F00', value: '"Alice"' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象',
header: 'MarkWord | KlassPtr -> User.class',
fields: [
{ name: 'name', value: '0x9F00 ("Alice")', ref: '0x9F00' },
{ name: 'age', value: '5', ref: null }
]
},
{
address: '0x7C00',
type: 'DirectByteBuffer 对象 (Java堆内壳)',
header: 'MarkWord | KlassPtr -> DirectByteBuffer',
fields: [
{ name: 'address', value: '0xFF88 (指向堆外)', ref: '0xFF88', highlight: true },
{ name: 'capacity', value: '1024', ref: null },
{ name: 'cleaner', value: 'Cleaner (PhantomReference)', ref: '0xFF88' }
],
highlight: true
}
],
directMemory: [
{
address: '0xFF88',
size: '1024 Bytes',
desc: 'OS 本地直接内存缓冲区 (减少一次堆内到堆外的中间拷贝)',
highlight: true
}
]
},
{
id: 13,
title: '步骤 14:main 方法执行完毕出栈,触发 GC 垃圾回收演示',
tag: '栈帧清空 & GC 回收',
activeLines: [8],
pc: '0x001D: return (main 结束)',
bytecode: '0x001D: return // main 栈帧出栈,局部变量表全部失效\n[GC] 触发 Young GC 可达性分析 (GC Roots Tracing)',
explanation: 'main 方法执行 return 后栈帧弹出,局部变量 user(0x1A2B) 和 buf(0x7C00) 随栈帧销毁,不再作为 GC Roots!当触发 GC 时,堆中的 User 对象和 DirectByteBuffer 对象变为不可达被回收;同时 DirectByteBuffer 绑定的 Cleaner(虚引用 PhantomReference)收到通知,自动执行 Unsafe.freeMemory 释放 0xFF88 堆外直接内存!',
nativeActive: null,
metaspace: {
classes: ['JvmDemo.class', 'ByteBuffer.class', 'User.class', 'DirectByteBuffer.class'],
constants: [{ name: 'BASE', value: '10 (GC Root 永久存活)', type: 'static final int' }],
methods: ['main(String[])', 'User.<init>', 'User.calc(int)']
},
frames: [],
stringPool: [
{ address: '0x9F00', value: '"Alice" (常量池驻留)' }
],
heapObjects: [
{
address: '0x1A2B',
type: 'User 实例对象 [无 GC Root 引用 -> 已回收]',
header: 'GC Marked: Unreachable (Garbage)',
fields: [
{ name: 'name', value: '0x9F00', ref: null },
{ name: 'age', value: '5', ref: null }
],
gcCollected: true
},
{
address: '0x7C00',
type: 'DirectByteBuffer [已回收 -> 触发 Cleaner]',
header: 'PhantomReference Enqueued -> Unsafe.freeMemory',
fields: [
{ name: 'address', value: '0xFF88 (已触发释放)', ref: '0xFF88' },
{ name: 'capacity', value: '1024', ref: null }
],
gcCollected: true
}
],
directMemory: [
{
address: '0xFF88',
size: '1024 Bytes [已由 Cleaner 释放]',
desc: 'Unsafe.freeMemory(0xFF88) 执行完毕,归还给操作系统',
gcCollected: true
}
]
}
];
export default function App() {
const [currentStepIdx, setCurrentStepIdx] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);
const [playSpeed, setPlaySpeed] = useState(2600); // ms
const [hoveredRef, setHoveredRef] = useState(null);
const step = EXECUTION_STEPS[currentStepIdx];
// 自动播放控制
useEffect(() => {
if (!isPlaying) return;
const timer = setInterval(() => {
setCurrentStepIdx((prev) => {
if (prev >= EXECUTION_STEPS.length - 1) {
setIsPlaying(false);
return prev;
}
return prev + 1;
});
}, playSpeed);
return () => clearInterval(timer);
}, [isPlaying, playSpeed]);
const handlePrev = () => {
setIsPlaying(false);
setCurrentStepIdx((prev) => Math.max(0, prev - 1));
};
const handleNext = () => {
setIsPlaying(false);
setCurrentStepIdx((prev) => Math.min(EXECUTION_STEPS.length - 1, prev + 1));
};
const handleReset = () => {
setIsPlaying(false);
setCurrentStepIdx(0);
};
// 引用地址颜色徽章辅助函数
const getRefBadgeClass = (refAddr) => {
if (!refAddr) return '';
const isHovered = hoveredRef === refAddr;
const base = 'px-1.5 py-0.5 rounded text-xs font-mono cursor-pointer transition-all duration-200 inline-flex items-center gap-1 border ';
if (refAddr === '0x1A2B') {
return base + (isHovered
? 'bg-emerald-500 text-slate-950 border-emerald-300 ring-2 ring-emerald-400 scale-105 font-bold'
: 'bg-emerald-950/80 text-emerald-300 border-emerald-700/60 hover:bg-emerald-900');
}
if (refAddr === '0x9F00') {
return base + (isHovered
? 'bg-amber-400 text-slate-950 border-amber-200 ring-2 ring-amber-300 scale-105 font-bold'
: 'bg-amber-950/80 text-amber-300 border-amber-700/60 hover:bg-amber-900');
}
if (refAddr === '0x7C00') {
return base + (isHovered
? 'bg-purple-400 text-slate-950 border-purple-200 ring-2 ring-purple-300 scale-105 font-bold'
: 'bg-purple-950/80 text-purple-300 border-purple-700/60 hover:bg-purple-900');
}
if (refAddr === '0xFF88') {
return base + (isHovered
? 'bg-cyan-400 text-slate-950 border-cyan-200 ring-2 ring-cyan-300 scale-105 font-bold'
: 'bg-cyan-950/80 text-cyan-300 border-cyan-700/60 hover:bg-cyan-900');
}
return base + 'bg-slate-800 text-slate-300 border-slate-700';
};
return (
<div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col font-sans selection:bg-indigo-500 selection:text-white">
{/* 顶部标题与播放控制栏 */}
<header className="bg-slate-900/90 border-b border-slate-800 px-4 py-3 sticky top-0 z-30 backdrop-blur-md">
<div className="max-w-[1600px] mx-auto flex flex-col lg:flex-row lg:items-center lg:justify-between gap-3">
{/* 左侧标题 */}
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-cyan-500 flex items-center justify-center shadow-lg shadow-indigo-500/20">
<Cpu className="w-6 h-6 text-white" />
</div>
<div>
<div className="flex items-center gap-2">
<h1 className="text-lg font-bold tracking-tight text-white">
JVM 运行时内存区域动态模拟器
</h1>
<span className="text-xs px-2 py-0.5 rounded-full bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-medium">
HotSpot 架构全景
</span>
</div>
<p className="text-xs text-slate-400">
实时追踪字节码执行、栈帧压入弹出、操作数栈计算、字符串常量池与 DirectByteBuffer 堆外内存引用链
</p>
</div>
</div>
{/* 右侧播放按钮与进度控制 */}
<div className="flex flex-wrap items-center gap-2 sm:gap-3">
<div className="flex items-center bg-slate-800/90 p-1 rounded-lg border border-slate-700">
<button
onClick={handleReset}
title="重置到第一步"
className="p-2 rounded-md hover:bg-slate-700 text-slate-300 hover:text-white transition"
>
<RotateCcw className="w-4 h-4" />
</button>
<button
onClick={handlePrev}
disabled={currentStepIdx === 0}
title="上一步"
className="p-2 rounded-md hover:bg-slate-700 text-slate-300 hover:text-white disabled:opacity-30 disabled:pointer-events-none transition"
>
<SkipBack className="w-4 h-4" />
</button>
<button
onClick={() => setIsPlaying(!isPlaying)}
className={`px-3.5 py-1.5 rounded-md font-medium text-xs flex items-center gap-1.5 transition shadow ${
isPlaying
? 'bg-amber-500 hover:bg-amber-600 text-slate-950'
: 'bg-indigo-600 hover:bg-indigo-500 text-white'
}`}
>
{isPlaying ? (
<>
<Pause className="w-3.5 h-3.5 fill-current" /> 暂停
</>
) : (
<>
<Play className="w-3.5 h-3.5 fill-current" /> 自动演示
</>
)}
</button>
<button
onClick={handleNext}
disabled={currentStepIdx === EXECUTION_STEPS.length - 1}
title="下一步"
className="p-2 rounded-md hover:bg-slate-700 text-slate-300 hover:text-white disabled:opacity-30 disabled:pointer-events-none transition"
>
<SkipForward className="w-4 h-4" />
</button>
</div>
{/* 速度选择 */}
<div className="flex items-center gap-1.5 bg-slate-800/70 px-2.5 py-1.5 rounded-lg border border-slate-700/80 text-xs">
<span className="text-slate-400">速度:</span>
{[
{ label: '慢', ms: 3800 },
{ label: '中', ms: 2600 },
{ label: '快', ms: 1400 }
].map((s) => (
<button
key={s.label}
onClick={() => setPlaySpeed(s.ms)}
className={`px-2 py-0.5 rounded transition ${
playSpeed === s.ms
? 'bg-indigo-500/30 text-indigo-200 border border-indigo-500/40 font-semibold'
: 'text-slate-400 hover:text-slate-200'
}`}
>
{s.label}
</button>
))}
</div>
{/* 步骤指示器 */}
<div className="text-xs font-mono bg-slate-950 px-3 py-1.5 rounded-lg border border-slate-800 text-slate-300">
STEP <span className="text-indigo-400 font-bold">{currentStepIdx + 1}</span> / {EXECUTION_STEPS.length}
</div>
</div>
</div>
{/* 14步可点击进度条 */}
<div className="max-w-[1600px] mx-auto mt-3 pt-2 border-t border-slate-800/80 flex items-center gap-1 overflow-x-auto pb-1">
{EXECUTION_STEPS.map((s, idx) => {
const isCurrent = idx === currentStepIdx;
const isDone = idx < currentStepIdx;
return (
<button
key={s.id}
onClick={() => {
setIsPlaying(false);
setCurrentStepIdx(idx);
}}
className={`group flex-1 min-w-[68px] text-left p-1.5 rounded-md border transition-all ${
isCurrent
? 'bg-indigo-950/90 border-indigo-500 shadow-sm shadow-indigo-500/20'
: isDone
? 'bg-slate-900/70 border-slate-800 hover:border-slate-700'
: 'bg-slate-950/40 border-slate-900 opacity-60 hover:opacity-100'
}`}
>
<div className="flex items-center justify-between text-[10px] font-mono mb-0.5">
<span className={isCurrent ? 'text-indigo-400 font-bold' : 'text-slate-500'}>
#{idx + 1}
</span>
<span className={`w-1.5 h-1.5 rounded-full ${
isCurrent ? 'bg-indigo-400 animate-ping' : isDone ? 'bg-emerald-500' : 'bg-slate-700'
}`} />
</div>
<div className={`text-[11px] truncate font-medium ${
isCurrent ? 'text-white' : 'text-slate-400'
}`}>
{s.tag}
</div>
</button>
);
})}
</div>
</header>
{/* 当前步骤核心原理解析横幅 */}
<section className="max-w-[1600px] w-full mx-auto px-4 pt-3">
<div className="bg-gradient-to-r from-indigo-950/70 via-slate-900 to-slate-900 border border-indigo-500/30 rounded-xl p-3.5 shadow-lg flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="space-y-1 flex-1">
<div className="flex items-center gap-2">
<span className="px-2 py-0.5 text-xs font-bold rounded bg-indigo-500 text-white">
{step.tag}
</span>
<h2 className="text-base font-bold text-indigo-200">
{step.title}
</h2>
</div>
<p className="text-xs sm:text-sm text-slate-300 leading-relaxed">
{step.explanation}
</p>
</div>
{/* 悬停引用提示小贴士 */}
<div className="shrink-0 bg-slate-950/80 border border-slate-800 rounded-lg px-3 py-2 text-xs text-slate-400 flex items-center gap-2">
<Sparkles className="w-4 h-4 text-amber-400 shrink-0" />
<div>
<div className="text-slate-200 font-medium">交互提示:悬停任意内存地址</div>
<div className="flex items-center gap-1.5 mt-1">
<span
onMouseEnter={() => setHoveredRef('0x1A2B')}
onMouseLeave={() => setHoveredRef(null)}
className={getRefBadgeClass('0x1A2B')}
>
0x1A2B (User)
</span>
<span
onMouseEnter={() => setHoveredRef('0x9F00')}
onMouseLeave={() => setHoveredRef(null)}
className={getRefBadgeClass('0x9F00')}
>
0x9F00 ("Alice")
</span>
<span
onMouseEnter={() => setHoveredRef('0xFF88')}
onMouseLeave={() => setHoveredRef(null)}
className={getRefBadgeClass('0xFF88')}
>
0xFF88 (直接内存)
</span>
</div>
</div>
</div>
</div>
</section>
{/* 主体:左侧源码与字节码 + 右侧 JVM 内存全景图 */}
<main className="max-w-[1600px] w-full mx-auto p-4 grid grid-cols-1 lg:grid-cols-12 gap-4 flex-1">
{/* 左侧栏:Java 源码 + 字节码指令集 + PC 计数器 (占 4 列) */}
<div className="lg:col-span-4 flex flex-col gap-4">
{/* 1. Java 源代码视图 */}
<div className="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-lg flex flex-col">
<div className="bg-slate-800/70 px-3.5 py-2 border-b border-slate-700/80 flex items-center justify-between">
<div className="flex items-center gap-2">
<Code2 className="w-4 h-4 text-indigo-400" />
<span className="text-xs font-bold text-slate-200">Java 源码 (JvmDemo.java)</span>
</div>
<span className="text-[11px] text-slate-400 font-mono">JDK 17 / HotSpot</span>
</div>
<div className="p-2 font-mono text-xs overflow-x-auto space-y-0.5">
{JAVA_CODE_LINES.map((item) => {
const isActive = step.activeLines.includes(item.line);
return (
<div
key={item.line}
className={`flex items-center px-2 py-1 rounded transition-colors ${
isActive
? 'bg-indigo-500/25 border-l-2 border-indigo-400 text-white font-semibold'
: 'text-slate-400 hover:bg-slate-800/40'
}`}
>
<span className="w-6 text-right pr-2 text-slate-600 select-none text-[11px]">
{item.line}
</span>
<span style={{ paddingLeft: `${item.indent * 14}px` }} className="whitespace-pre">
{item.code}
</span>
{isActive && (
<span className="ml-auto flex items-center gap-1 text-[10px] text-indigo-300 bg-indigo-950/90 px-1.5 py-0.5 rounded border border-indigo-500/40">
<ChevronRight className="w-3 h-3" /> 执行中
</span>
)}
</div>
);
})}
</div>
</div>
{/* 2. 程序计数器 (PC Register) & 当前字节码指令 */}
<div className="bg-slate-900 border border-indigo-500/40 rounded-xl overflow-hidden shadow-lg">
<div className="bg-indigo-950/60 px-3.5 py-2 border-b border-indigo-500/30 flex items-center justify-between">
<div className="flex items-center gap-2">
<Terminal className="w-4 h-4 text-indigo-400" />
<span className="text-xs font-bold text-indigo-200">
程序计数器 (PC Register) & 字节码执行引擎
</span>
</div>
<span className="text-[10px] px-1.5 py-0.5 rounded bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
线程私有
</span>
</div>
<div className="p-3.5 space-y-3">
<div className="flex items-center justify-between bg-slate-950 px-3 py-2 rounded-lg border border-slate-800">
<span className="text-xs text-slate-400">当前 PC 指令地址:</span>
<span className="text-xs font-mono font-bold text-amber-400 flex items-center gap-1.5">
<Zap className="w-3.5 h-3.5 text-amber-400 animate-pulse" />
{step.pc}
</span>
</div>
<div>
<div className="text-[11px] text-slate-400 mb-1.5 flex items-center justify-between">
<span>正在执行的字节码指令 (Bytecode Instruction):</span>
<span className="font-mono text-[10px] text-slate-500">javap -c</span>
</div>
<pre className="bg-slate-950 text-emerald-300 p-3 rounded-lg border border-slate-800 font-mono text-xs whitespace-pre-wrap leading-relaxed">
{step.bytecode}
</pre>
</div>
</div>
</div>
{/* 3. 本地方法栈 (Native Method Stack) */}
<div className={`rounded-xl border transition-all duration-300 overflow-hidden ${
step.nativeActive
? 'bg-rose-950/30 border-rose-500/60 shadow-lg shadow-rose-500/10'
: 'bg-slate-900/60 border-slate-800/80'
}`}>
<div className="px-3.5 py-2 border-b border-slate-800 flex items-center justify-between">
<div className="flex items-center gap-2">
<Cpu className={`w-4 h-4 ${step.nativeActive ? 'text-rose-400 animate-spin' : 'text-slate-500'}`} />
<span className="text-xs font-bold text-slate-200">
本地方法栈 (Native Method Stack - JNI)
</span>
</div>
<span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400">
线程私有 / C & C++
</span>
</div>
<div className="p-3 text-xs">
{step.nativeActive ? (
<div className="space-y-1.5 bg-rose-950/60 border border-rose-500/40 rounded-lg p-2.5">
<div className="flex items-center justify-between">
<span className="text-rose-300 font-bold font-mono">{step.nativeActive.method}</span>
<span className="px-1.5 py-0.5 text-[10px] bg-rose-500 text-white rounded font-bold">
JNI 激活
</span>
</div>
<div className="text-slate-300 text-[11px] font-mono">
底层动态库调用: <span className="text-amber-300">{step.nativeActive.lib}</span>
</div>
<div className="text-slate-300 text-[11px] font-mono flex items-center gap-1">
返回值:
<span
onMouseEnter={() => setHoveredRef('0xFF88')}
onMouseLeave={() => setHoveredRef(null)}
className={getRefBadgeClass('0xFF88')}
>
{step.nativeActive.returnVal}
</span>
</div>
</div>
) : (
<div className="text-slate-500 text-center py-2 font-mono text-[11px]">
[ 空闲 - 当前未执行 native 修饰的本地 C/C++ 方法 ]
</div>
)}
</div>
</div>
</div>
{/* 右侧栏:JVM 运行时数据区全景 (占 8 列) */}
<div className="lg:col-span-8 grid grid-cols-1 md:grid-cols-12 gap-4">
{/* 中间列:Java 虚拟机栈 (JVM Stack) - 占 6 列 */}
<div className="md:col-span-6 bg-slate-900 border border-blue-500/30 rounded-xl flex flex-col overflow-hidden shadow-lg">
<div className="bg-blue-950/50 px-4 py-2.5 border-b border-blue-500/30 flex items-center justify-between">
<div className="flex items-center gap-2">
<Layers className="w-4 h-4 text-blue-400" />
<div>
<h3 className="text-xs font-bold text-blue-200">Java 虚拟机栈 (JVM Stack)</h3>
<p className="text-[10px] text-slate-400">每个方法调用对应一个栈帧(后进先出 LIFO)</p>
</div>
</div>
<span className="text-[10px] px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">
线程私有
</span>
</div>
<div className="p-3.5 flex-1 flex flex-col-reverse justify-start gap-3 bg-slate-950/40 min-h-[420px]">
{step.frames.length === 0 ? (
<div className="my-auto text-center text-slate-500 py-12 space-y-2">
<Layers className="w-8 h-8 mx-auto opacity-30" />
<p className="text-xs font-mono">
{currentStepIdx === 0
? '等待 main() 方法入栈...'
: 'main() 栈帧已弹出,线程执行完毕(GC Roots 已解除)'}
</p>
</div>
) : (
step.frames.map((frame, fIdx) => {
const isTopFrame = fIdx === step.frames.length - 1;
return (
<div
key={frame.id}
className={`rounded-xl border p-3 transition-all duration-300 ${
isTopFrame
? 'bg-slate-900 border-blue-500/70 shadow-md shadow-blue-500/10'
: 'bg-slate-900/50 border-slate-800 opacity-75'
}`}
>
{/* 栈帧头部 */}
<div className="flex items-center justify-between pb-2 mb-2.5 border-b border-slate-800">
<div className="flex items-center gap-2">
<span className={`px-2 py-0.5 text-[10px] font-bold rounded ${
isTopFrame ? 'bg-blue-600 text-white' : 'bg-slate-800 text-slate-400'
}`}>
{isTopFrame ? '当前活动栈帧 (栈顶)' : '挂起栈帧 (调用者)'}
</span>
<span className="font-mono text-xs font-bold text-white">
{frame.name}
</span>
</div>
</div>
{/* 栈帧内部 1:局部变量表 + 操作数栈 并排 */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
{/* 1. 局部变量表 */}
<div className="bg-slate-950/90 border border-slate-800 rounded-lg p-2.5">
<div className="text-[11px] font-semibold text-blue-300 mb-2 flex items-center justify-between">
<span>① 局部变量表 (Local Vars)</span>
<span className="text-[10px] text-slate-500 font-mono">Slot 槽位</span>
</div>
<div className="space-y-1.5">
{frame.locals.map((loc) => (
<div
key={loc.slot}
className={`flex items-center justify-between text-xs px-2 py-1 rounded border font-mono ${
loc.highlight
? 'bg-blue-500/20 border-blue-400 text-white animate-pulse'
: 'bg-slate-900/80 border-slate-800/90 text-slate-300'
}`}
>
<span className="text-[11px] text-slate-400">
[{loc.slot}] <strong className="text-slate-200">{loc.name}</strong>
</span>
{loc.ref ? (
<span
onMouseEnter={() => setHoveredRef(loc.ref)}
onMouseLeave={() => setHoveredRef(null)}
className={getRefBadgeClass(loc.ref)}
>
<Link2 className="w-3 h-3" />
{loc.value}
</span>
) : (
<span className="text-amber-300 text-[11px]">{loc.value}</span>
)}
</div>
))}
</div>
</div>
{/* 2. 操作数栈 */}
<div className="bg-slate-950/90 border border-slate-800 rounded-lg p-2.5 flex flex-col">
<div className="text-[11px] font-semibold text-amber-300 mb-2 flex items-center justify-between">
<span>② 操作数栈 (Operand Stack)</span>
<span className="text-[10px] text-slate-500 font-mono">LIFO 计算台</span>
</div>
<div className="flex-1 flex flex-col-reverse justify-start gap-1.5 min-h-[75px] bg-slate-900/50 rounded p-1.5 border border-dashed border-slate-800">
{frame.operandStack.length === 0 ? (
<div className="my-auto text-center text-[11px] text-slate-600 font-mono">
[ 栈空 ]
</div>
) : (
frame.operandStack.map((op, idx) => (
<div
key={idx}
className={`px-2 py-1 rounded text-xs font-mono flex items-center justify-between border ${
op.highlight
? 'bg-amber-500/20 border-amber-400 text-amber-200 shadow-sm'
: 'bg-slate-800 border-slate-700 text-slate-300'
}`}
>
<span className="text-[11px] truncate">{op.desc}</span>
{op.ref ? (
<span
onMouseEnter={() => setHoveredRef(op.ref)}
onMouseLeave={() => setHoveredRef(null)}
className={getRefBadgeClass(op.ref)}
>
{op.value}
</span>
) : (
<span className="font-bold text-amber-300">{op.value}</span>
)}
</div>
))
)}
</div>
</div>
</div>
{/* 栈帧内部 2:动态链接 & 方法返回地址 */}
<div className="mt-2 pt-2 border-t border-slate-800/80 grid grid-cols-2 gap-2 text-[11px] font-mono text-slate-400">
<div className="bg-slate-950/60 px-2 py-1 rounded border border-slate-800/60 truncate">
<span className="text-slate-500">③ 动态链接: </span>
<span className="text-indigo-300">{frame.dynamicLink}</span>
</div>
<div className="bg-slate-950/60 px-2 py-1 rounded border border-slate-800/60 truncate">
<span className="text-slate-500">④ 返回地址: </span>
<span className="text-emerald-300">{frame.returnAddr}</span>
</div>
</div>
</div>
);
})
)}
</div>
</div>
{/* 最右列:Java 堆 + 元空间 + 堆外直接内存 (占 6 列) */}
<div className="md:col-span-6 flex flex-col gap-4">
{/* 1. Java 堆 (Heap - 含 Eden 区与字符串常量池) */}
<div className="bg-slate-900 border border-emerald-500/30 rounded-xl overflow-hidden shadow-lg flex-1 flex flex-col">
<div className="bg-emerald-950/50 px-4 py-2.5 border-b border-emerald-500/30 flex items-center justify-between">
<div className="flex items-center gap-2">
<Database className="w-4 h-4 text-emerald-400" />
<div>
<h3 className="text-xs font-bold text-emerald-200">Java 堆 (Heap - 对象实例 & 字符串常量池)</h3>
<p className="text-[10px] text-slate-400">存放所有 new 出来的对象实体与 String Table</p>
</div>
</div>
<span className="text-[10px] px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">
线程共享 / GC 主战场
</span>
</div>
<div className="p-3.5 space-y-3 flex-1 flex flex-col justify-between">
{/* 普通对象区 (Eden) */}
<div className="space-y-2">
<div className="text-[11px] font-semibold text-emerald-300 flex items-center justify-between">
<span>Eden 年轻代实例分配区:</span>
<span className="text-[10px] font-mono text-slate-500">对象头 + 实例数据 + 对齐填充</span>
</div>
{step.heapObjects.length === 0 ? (
<div className="text-center py-6 bg-slate-950/50 rounded-lg border border-dashed border-slate-800 text-slate-500 text-xs font-mono">
[ 堆中暂无实例对象 ]
</div>
) : (
<div className="space-y-2.5">
{step.heapObjects.map((obj) => {
const isHovered = hoveredRef === obj.address;
return (
<div
key={obj.address}
onMouseEnter={() => setHoveredRef(obj.address)}
onMouseLeave={() => setHoveredRef(null)}
className={`p-3 rounded-lg border transition-all duration-300 ${
obj.gcCollected
? 'bg-rose-950/20 border-rose-500/40 opacity-60 line-through decoration-rose-500'
: isHovered || obj.highlight
? 'bg-emerald-950/40 border-emerald-400 ring-2 ring-emerald-500/30 shadow-lg'
: 'bg-slate-950/80 border-slate-800'
}`}
>
<div className="flex items-center justify-between mb-1.5">
<span className="font-bold text-xs text-white flex items-center gap-1.5">
{obj.gcCollected && <Trash2 className="w-3.5 h-3.5 text-rose-400" />}
{obj.type}
</span>
<span className={getRefBadgeClass(obj.address)}>
地址: {obj.address}
</span>
</div>
<div className="text-[10px] font-mono text-slate-400 bg-slate-900 px-2 py-1 rounded mb-2 border border-slate-800/80">
[对象头 Header] {obj.header}
</div>
<div className="grid grid-cols-2 gap-1.5">
{obj.fields.map((f) => (
<div
key={f.name}
className={`px-2 py-1 rounded text-xs font-mono flex items-center justify-between border ${
f.highlight
? 'bg-emerald-500/20 border-emerald-400 text-white'
: 'bg-slate-900/90 border-slate-800 text-slate-300'
}`}
>
<span className="text-slate-400">{f.name}:</span>
{f.ref ? (
<span
onMouseEnter={(e) => {
e.stopPropagation();
setHoveredRef(f.ref);
}}
className={getRefBadgeClass(f.ref)}
>
{f.value}
</span>
) : (
<span className="text-emerald-300">{f.value}</span>
)}
</div>
))}
</div>
</div>
);
})}
</div>
)}
</div>
{/* 字符串常量池 (String Pool) */}
<div className="pt-2 border-t border-slate-800">
<div className="text-[11px] font-semibold text-amber-300 mb-1.5 flex items-center justify-between">
<span>字符串常量池 (String Table / String Pool - 位于堆中):</span>
<span className="text-[10px] font-mono text-slate-500">intern() 缓存复用</span>
</div>
{step.stringPool.length === 0 ? (
<div className="text-center py-2.5 bg-slate-950/50 rounded-lg border border-dashed border-slate-800 text-slate-500 text-xs font-mono">
[ 字符串常量池尚未加载字面量 ]
</div>
) : (
<div className="flex flex-wrap gap-2">
{step.stringPool.map((str) => {
const isHovered = hoveredRef === str.address;
return (
<div
key={str.address}
onMouseEnter={() => setHoveredRef(str.address)}
onMouseLeave={() => setHoveredRef(null)}
className={`px-3 py-1.5 rounded-lg border text-xs font-mono flex items-center gap-2 transition-all ${
isHovered || str.highlight
? 'bg-amber-950/60 border-amber-400 ring-2 ring-amber-400/30 text-white'
: 'bg-slate-950 border-slate-800 text-amber-200'
}`}
>
<span className={getRefBadgeClass(str.address)}>{str.address}</span>
<span>→</span>
<span className="font-bold text-amber-300">{str.value}</span>
</div>
);
})}
</div>
)}
</div>
</div>
</div>
{/* 2. 元空间 / 方法区 (Metaspace) */}
<div className="bg-slate-900 border border-amber-500/30 rounded-xl overflow-hidden shadow-lg">
<div className="bg-amber-950/40 px-4 py-2 border-b border-amber-500/30 flex items-center justify-between">
<div className="flex items-center gap-2">
<HardDrive className="w-4 h-4 text-amber-400" />
<h3 className="text-xs font-bold text-amber-200">
元空间 / 方法区 (Metaspace - 类元数据 & 静态常量)
</h3>
</div>
<span className="text-[10px] px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">
线程共享 / 本地内存
</span>
</div>
<div className="p-3 grid grid-cols-1 sm:grid-cols-2 gap-2.5 text-xs font-mono">
<div className="bg-slate-950 p-2.5 rounded-lg border border-slate-800">
<div className="text-[11px] text-slate-400 mb-1">已加载类信息 (Klass Metadata):</div>
<div className="flex flex-wrap gap-1">
{step.metaspace.classes.map((cls) => (
<span
key={cls}
className="px-2 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 text-[11px]"
>
{cls}
</span>
))}
</div>
</div>
<div className="bg-slate-950 p-2.5 rounded-lg border border-slate-800">
<div className="text-[11px] text-slate-400 mb-1">静态常量池 (Static Constants):</div>
{step.metaspace.constants.map((c) => (
<div key={c.name} className="text-emerald-300 text-[11px]">
{c.type} <strong className="text-white">{c.name}</strong> = {c.value}
</div>
))}
</div>
</div>
</div>
{/* 3. 堆外内存 / 直接内存 (Off-Heap Direct Memory) */}
<div className={`rounded-xl border transition-all duration-300 overflow-hidden shadow-lg ${
step.directMemory.length > 0
? 'bg-cyan-950/30 border-cyan-400/70 shadow-cyan-500/10'
: 'bg-slate-900 border-slate-800'
}`}>
<div className="bg-cyan-950/50 px-4 py-2 border-b border-cyan-500/30 flex items-center justify-between">
<div className="flex items-center gap-2">
<Zap className="w-4 h-4 text-cyan-400" />
<h3 className="text-xs font-bold text-cyan-200">
堆外直接内存 (Direct Memory - NIO 零中间复制缓冲区)
</h3>
</div>
<span className="text-[10px] px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">
OS 本地内存 (非 JVM 堆)
</span>
</div>
<div className="p-3">
{step.directMemory.length === 0 ? (
<div className="text-center py-2.5 text-slate-500 text-xs font-mono">
[ 尚未调用 ByteBuffer.allocateDirect() 分配直接内存 ]
</div>
) : (
step.directMemory.map((dm) => {
const isHovered = hoveredRef === dm.address;
return (
<div
key={dm.address}
onMouseEnter={() => setHoveredRef(dm.address)}
onMouseLeave={() => setHoveredRef(null)}
className={`p-2.5 rounded-lg border font-mono text-xs transition-all ${
dm.gcCollected
? 'bg-rose-950/30 border-rose-500/40 text-slate-400 line-through'
: isHovered || dm.highlight
? 'bg-cyan-950/80 border-cyan-300 ring-2 ring-cyan-400/40 text-white'
: 'bg-slate-950 border-cyan-800 text-cyan-200'
}`}
>
<div className="flex items-center justify-between mb-1">
<span className="font-bold text-cyan-300 flex items-center gap-1.5">
<span className={getRefBadgeClass(dm.address)}>{dm.address}</span>
<span>容量: {dm.size}</span>
</span>
<span className="text-[10px] px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-200">
栈 buf(0x7C00) → 堆 DirectByteBuffer → 堆外 0xFF88
</span>
</div>
<div className="text-[11px] text-slate-300">{dm.desc}</div>
</div>
);
})
)}
</div>
</div>
</div>
</div>
</main>
</div>
);
}总结
JVM 的内存模型绝不是孤立的概念背诵,而是与类加载机制、字节码执行、调用指令分派以及垃圾收集器高度结合的紧密有机体:
- 栈管运行,堆管存储:方法调用通过线程私有的虚拟机栈帧实现,对象的实体分配在线程共享的 Java 堆中,栈帧中的局部变量表仅保存指向堆中实体的指针。
- 操作数栈是工作台:所有的计算(如
iadd)和参数入栈,都需要通过压栈与弹出操作完成。 - 元空间存储元信息:JDK 8 移除了永久代,使用本地内存的元空间(Metaspace)存放类元数据、常量池和方法字节码。
- 堆外直接内存实现高吞吐:NIO 通过 JNI 申请操作系统的本地物理内存,结合
Cleaner虚引用在 Java 对象被垃圾回收时自动释放底层的直接内存。
希望通过这个可交互的动态模拟器,能够帮助大家彻底建立起 JVM 运行时数据区的立体心智模型!