对应官网地址: Run-Time Data Areas
4. 运行时数据区(Run-Time Data Areas)
类文件被装载器装载进去之后,类中的内容(比如变量、常量、方法、对象)需要被存储起来。
4.1 图解
4.2 常规理解
4.2.1 Method Area (方法区)
方法区是各个线程所共享的内存区域,在虚拟机启动时创建。
用于存储已被虚拟机加载到的类信息、常量、静态变量、即时编译器编译后的代码等数据。
重点
-
方法区在 JDK8 中就是 MetaSpace , JDK7就是 Perm Space
-
Run-Time Constant Pool 用于存放编译时期生成的各种自变量和符号引用,这部分内容将在类加载后进入方法区的运行时常量池中存放。
Each run-time constant pool is allocated from the Java Virtual Machine's method area (§2.5.4).
常量池内存不足是就会报OutOfMemoryError
When creating a class or interface, if the construction of the run-time constant pool requires more memory than can be made available in the method area of the Java Virtual Machine, the Java Virtual Machine throws an OutOfMemoryError.
类装载第二步:将这个字节流所代表的静态存储结构转化为方法区的运行时数据结构。
4.2.2 Heap(堆)
Java 堆是 Java 虚拟机所管理内存最大的一块,在虚拟机启动时创建,被所有线程共享
java 对象实例以及数组都是在对上进行分配
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堆中生成一个代表这个类的 java.lang.Class
对象,作为方法区这些数据的访问入口
4.2.3 Java Virtual Machine Stacks (虚拟机栈)
每一个jvm线程都有一个虚拟机栈。
一个 Java 线程的运行状态,由一个虚拟机栈来保存,虚拟机栈随着线程的创建而创建
每一个被线程执行的方法,为该栈中的栈帧,即每一个方法对应一个栈帧。
调用一个方法,就会向栈中压入一个栈帧;一个方法调用完成,就会把该栈帧从栈中弹出。
栈的内部数据原理: 先进后出,后进先出。
Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread.
图解:
4.2.4 The pc Register (程序计数器)
程序计数器占用的内存空间很小,由于 Java虚拟机的多线程是通过线程轮流切换,并分配处理器执行时间的方式实现的,在任意时刻,一个处理器只会执行一条线程中的指令。
因此,为了线程切换后能够恢复到正确的位置,每条线程都需要一个独立的程序计数器(线程私有)。
线程执行java方法,则计数器记录的是 正在执行虚拟机字节码指令的地址;
线程执行native方法,则计数器为空。
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. If the method currently being executed by the thread is native, the value of the Java Virtual Machine's pc register is undefined. The Java Virtual Machine's pc register is wide enough to hold a returnAddress or a native pointer on the specific platform.
4.2.5 Native Method Stacks( 本地方法栈)
如果当前线程执行的方法是 Native 类型,这些方法就会在本地方法栈中之心
When I let go of what I am , I become what I might be.
走出舒适圈,遇见更好的自己。