文章目录
环境
运行时数据区概览图
线程隔离的数据区
The pc Register
The Java Virtual Machine can support many threads of execution at once (JLS §17)Each Java Virtual Machine thread has its own pc (program counter) register.At any point, each Java Virtual Machine thread is executing the code of a single method, namely the current method (§2.6) for that thread. If that method is not native, the pc register contains the address of the Java Virtual Machine instruction currently being executed.
java虚拟机可以支持多个线程同时执行。每个线程有自己的程序计数器。在任何时刻,每个java虚拟机都在执行一个方法,就是当前线程正在执行的方法。如果这个方法不是native方法,则程序计数器会包含正在执行的Java虚拟机指令的地址。 即当前线程所执行的字节码的行号指示器。
说人话就是记录下一个指令在哪。
Java Virtual Machine Stacks
Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread. A Java Virtual Machine stack stores frames (§2.6).
每个线程都有一个与线程同时创建的私有的Java虚拟机栈。栈里存储的是栈帧。
它的生命周期与线程相同。虚拟机栈描述的是Java方法执行的线程内存模型:每个方法被执行的时候,Java虚拟机都会同步创建一个栈帧(Stack Frame)用于存储局部变量表、操作数栈、动态连接、方法出口等信息。每一个方法被调用直至执行完毕的过程,就对应着一个栈帧在虚拟机栈中从入栈到出栈的过程。
Frame
A frame is used to store data and partial results, as well as to perform dynamic linking, return values for methods, and dispatch exceptions.
栈帧用来存储数据和部分结果和执行动态链接、方法返回值和调度异常。
栈帧结构
- Local Variables(局部变量表)
- Operand Stack(操作数栈)
- Dynamic Linking
- return address
Native Method Stacks
An implementation of the Java Virtual Machine may use conventional stacks.
本地方法栈(Native Method Stacks)与虚拟机栈所发挥的作用是非常相似的,其区别只是虚拟机栈为虚拟机执行Java方法(也就是字节码)服务,而本地方法栈则是为虚拟机使用到的本地(Native)方法服务。
由所有线程共享的数据区
Heap
The Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.
所有Java虚拟机线程之间共享堆。所有类的实例和数组在堆中分配内存。
Method Area
The Java Virtual Machine has a method area that is shared among all Java Virtual Machine threads. The method area is analogous to the storage area for compiled code of a conventional language or analogous to the “text” segment in an operating system process. It stores per-class structures such as the run-time constant pool, field and method data, and the code for methods and constructors, including the special methods (§2.9) used in class and instance initialization and interface initialization.
所有线程共享方法区。方法区存储了每个类的结构。方法区是一个逻辑概念。在 jdk1.8 之前,方法区指的就是 Perm Space 。字符串常量位于 Perm Space。FGC 不会清理。Perm Space 的大小启动的时候指定,不能变。
jdk1.8之后,方法区指的是 Meta Space。 字符串常量位于堆。方法区会触发FGC清理 。不设定大小的话,最大就是物理内存。
Run-Time Constant Pool
A run-time constant pool is a per-class or per-interface run-time representation of the constant_pool table in a class file (§4.4).
运行时常量池(RuntimeConstantPool)是方法区的一部分。Class文件中除了有类的版本、字段、方法、接口等描述信息外,还有一项信息是常量池表(ConstantPoolTable),用于存放编译期生成的各种字面量与符号引用,这部分内容将在类加载后存放到方法区的运行时常量池中。
参考资料
- The Java® Virtual Machine Specification
- Java SE 8 Edition
- 深入理解Java虚拟机(第3版)