Note 1: All threads mentioned below are by default referred to as “Java Virtual machine threads” unless otherwise specified.

Note 2: Be careful not to confuse Stack and Heap with Java(VM) Stack and Java Heap. The Java virtual machine is a higher level abstraction on top of the operating system and can be considered a virtual computer. The Memory partition of the Java VIRTUAL machine does not correspond to that of the OPERATING system. The implementation of the Java virtual machine itself is an application written in another language, and the data allocated in the Java Stack from the perspective of the Java language program can be allocated in the Heap from the perspective of the program implementing the virtual machine.

The Memory structure of the Java VIRTUAL machine is different from the Java Memory Model, which focuses on multi-threading.

We certainly want to define the concept and purpose of each region precisely, but before (or after) doing so, should we consider why the JVM’s memory structure is divided this way?

Private data is divided mainly according to different data update frequency, access speed requirements, garbage collection management. The working memory area of the thread, which requires high speed and is limited by the scarcity of resources on high-speed read and write devices, is divided by the JVM into PC registers, stacks, which store the count of current method operations and local variables (basic types and references). For class structure information, constant and static methods with low update frequency, “method area” is divided. For object instances that occupy a large amount of capacity, Java Heap is divided. In order to distinguish the processing of Java Method and Native Method, the Stack is divided into JVM Stack(Java VIRTUAL machine Stack area) and Native Method Stack(local Method Stack). These are the five largest memory areas of the JVM.

1, PC register, thread private, small, fast; JVM Stack, thread private, small, fast; 3, Native Method Stack, thread private, small, fast; Java Heap, shared area, large, dynamic capacity allocation, slow; 5. Method area, Sharing area, middle;

The name is Chinese and English

* Runtime Data Areas – (Run-time Data Areas) – PC Registers – (Program Counter Register) – Java Virtual Machine Stack – (JVM Stack) * Stack frames – (Frame) * Local variable table – (Local Variables) * Operand Stack – (Dynamic Linking) – Java Heap – (Java Heap) – Method Area * Runtime Constant Pool – (Runtime Constant Pool) – (Native Method Stack)


Zone definitions (JVM specification)

The JVM defines several run-time data areas that can be used during a program’s execution, corresponding to the lifetime of the JVM or thread.

PC register: Each thread has its own PC register. If the current method being executed by the thread is not native, the PC register holds the address of the bytecode instructions being executed by the JVM, or undefined if it is native.

JVM Stack: Each thread has its own private JVM Stack. It is created at the same time as the thread to store the Frame. Similar to the Stack in traditional language (C), the JVM Stack is used to store local variables and some procedure results. It also plays an important role in method calls and returns. Because the JVM Stack is not affected by anything other than the loading and unloading of frames, frames can be allocated in the heap.

Native method Stack: JVM implementations may use a traditional C Stack to support execution of native methods. This Stack is called the native method Stack. When a JVM implements an instruction set interpreter in another language, the native method stack is also used. This stack is typically allocated by thread when a thread is created.

Java Heap: In the JVM, the Heap is an area of runtime memory that can be shared by threads and where memory is allocated for all class instances and data objects. Heap is created at JVM startup and stores various objects managed by the ASMS/GC that need not or cannot be explicitly destroyed.

Method area: In the JVM, a method area is an area of runtime memory that can be shared by threads. It stores structural information for each class, such as runtime constant pools, field and method data, constructors, and bytecode content for common methods. The method area is created when the virtual machine is started.

Runtime constant pool: This pool is a runtime representation of a constant pool for each class or interface, which contains several different constants: from numeric literals known at compile time to method or field references that must be resolved at run time to obtain. A run-time constant pool acts like a Symbol Table in a traditional language, except that it stores a broader range of data than a Symbol Table normally does. Each run-time constant pool is allocated in the Java Virtual machine’s method area, and the corresponding run-time constant pool is created after classes and interfaces are loaded into the virtual machine.

Stack Frames: Frames are data structures used to store data and partial process results. They are also used to handle dynamic linking, method return values, and exception dispatch. A Frame is created with a method call and destroyed at the end of the method — either normal completion or exception completion (throwing no exceptions that are not caught in the method) counts as method completion. Frames are allocated in storage within the JVM Stack, and each Frame has its own local table of variables, operand Stack, and runtime constant pool references to the class to which the current method belongs.

The size of the local variable table and operand stack is determined at compile time and is saved and made available to Frame through the method’s Code property. Therefore, the size of the Frame capacity depends solely on the IMPLEMENTATION of the JVM and the amount of memory that can be allocated when a method is called.

In a thread, only the Frame of the currently executing Method is active, which is called Current Frame (Current stack Frame, CF for short). The corresponding Method is called Current Method(CM for short), and the Class that defines this Method is called Current Class. Operations on the local variator and operand stack usually refer to operations on the local variator and operand stack on the current stack frame.

If CM calls another method, or if CM finishes, the method’s Frame is no longer CF. When a new method is called, a new Frame is created and becomes a new CF as program control is transferred to the new method. When the method returns, the CF returns the execution result of the method to the previous Frame. After the method returns, the CF is discarded and the previous Frame becomes CF again.

It is important to note that frames are private to the thread, and frames of different threads cannot be accessed or referenced by each other.

Local variable table: Each Frame contains a list of variables called the local variable table. Its length is determined at compile time and is stored in the binary representation of the class and interface, which is saved and made available to Frame through the Code property of the method. This area stores 8 basic types as well as the data of Reference and returnAddress types, in which the data of double and long types occupy two variable bits, and the rest occupy one. The JVM uses a local variator to pass arguments to a method call. When a method is called, its arguments are passed to successive local variator positions starting at 0. In particular, when an instance method is called, the 0th local variable must be used to store a reference to the object on which the instance method is called (that is, the this keyword). Subsequent parameters will be passed to a continuous local variable table position starting at 1.

Operand stack: Each Frame contains a LIFO (LIFO) called the operand stack. Its length is determined at compile time and is stored in the binary representation of the class and interface, which is saved and made available to Frame through the Code property of the method. On the premise that the context is clear and there is no misunderstanding, we often refer to “the operand stack of the current stack frame” as “the operand stack”.

The Frame to which the operand stack belongs is empty when it is created. The JVM provides bytecode instructions for copying constant or variable values from the fields of a local variable table or object instance to the operand stack, as well as instructions for fetching data from the operand stack, manipulating data, and pushing the results of operations back onto the stack. When a method is called, the operand stack is also used to prepare the parameters of the calling method and to receive the results returned by the method. (See $2.6.2 for process details)

Dynamic linking: Each Frame contains a reference to the runtime constant pool to support the current method’s code implementation of dynamic linking.

In-depth understanding of districts

1. PC registers

The PC Register (Program Counter Register) is a small memory space that can be viewed as a line number indicator of the bytecode being executed by the current thread. In the conceptual model of virtual machine, bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to be executed, and basic functions such as branch, loop, jump, exception handling, thread recovery and so on need to be completed by this counter.

Because JVM multithreading is implemented by alternating the allocation of CPU execution time, only one CPU/ kernel will execute instructions from one thread at a given time. In order for threads to switch back to the correct execution location, each thread needs to have a private, independent PC register, which is not affected by each thread. We call this type of memory area “thread-private” memory.

If the thread is currently executing a Java method, the PC register records the address of the virtual machine bytecode instruction being executed.

If the thread is executing a native method, its value is null.

2.JVM Stack

Like PC registers, the JVM Stack is thread private. It has the same life cycle as a thread. The JVM Stack describes the memory model of Java method execution: as each method executes, a Frame is created to store information about local variables, operand stacks, dynamic links, method exits, and so on. Each method from invocation to completion corresponds to a Frame being pushed onto and off the JVM Stack.

The division of Java memory regions is far more complex than the crude division of Java memory into Heap and Stack. The “Stack” is now referred to as the JVM Stack, or the local variable scale portion of the JVM Stack (directly bypiting the Stack and Frame).

Local variable table, which stores 8 basic data types known at compile time, and object reference type (reference type, not the object itself, may only be a reference pointer to the starting address of the object, They can also point to a handle representing an object or other location associated with that object) and the returnAddress type (which points to the address of a bytecode instruction). The space needed for the local variable table is allocated at compile time. When entering a method, how much local variable space the method needs to allocate in the frame is completely determined, and the size of the local variable table does not change during the method run.

A StackOverflowError is raised when a thread request allocates more stack capacity than the maximum allowed by the JVM.

An OutOfMemoryError is raised if the JVM can be dynamically extended and the extension action has been attempted, but there is currently not enough memory to complete the extension, or there is not enough memory to create the corresponding JVM Stack when a new thread is created.

StackOverflowError: request > stack.max;

OutOfMemoryError means request > allocatable memory;

3. Local method stack

The role of the Native method Stack is very similar to that of the JVM Stack, except that the JVM Stack serves the Java methods used by the VIRTUAL machine, while the Native method Stack serves the Native methods used by the virtual machine.

The virtual machine specification does not enforce the language, usage mode, and data structure of methods in the local method stack. There are even virtual machines (such as HotSpot) that simply combine the local method Stack with the JVM Stack. As with JVM Stack, StackOverflowError and OutOfMemoryError exceptions are thrown.

4.Java Heap

For most applications, the Java Heap is the largest chunk of memory managed by the JVM. It is an area of memory shared by all threads and created at virtual machine startup. The sole purpose of this zone is to hold object instances, and almost all object instances are allocated memory here.

The Java Heap is the primary area managed by the GC. Because collectors now basically use generational collection algorithms, so the Java Heap is subdivided into: new generation and old generation; Finer Eden space, From Survivor space, To Survivor space, etc. However, no matter how you divide it, it has nothing to do with what you store. Whatever area you store is an object instance.

It can be either fixed size or extended, but most virtual machines are implemented as extensible (-xmx and -xMS). OutOfMemoryError is thrown if there is no memory in the heap to complete the instance allocation and the heap can no longer be extended.

5. Methods area

Like the Java Heap, the method area is an area of memory shared by individual threads that stores information about classes that have been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, and so on. Although the JVM specification describes the method area as a logical part of the Heap, it has a separate name, non-heap, that is supposed to be attached to the Java Heap partition.

The Java Virtual Machine specification is very relaxed about method areas, and you can choose not to implement garbage collection. Garbage collection is relatively rare in this area, but the non-data entry method area is as “permanent” as the name of the permanent generation. The target of memory reclamation in this area is mainly for constant pool reclamation and type unloading. Generally speaking, the “performance” of the reclamation in this area is not satisfactory, especially for type unloading, but the reclamation in this part of the area is indeed necessary.

Run-time constant pool

The runtime constant pool is part of the method area. In addition to the Class version, field, method, interface, and other description information, the Class file contains the constant pool, which is used to store various literals and symbolic references generated at compile time. This part of the constant pool will be stored in the runtime constant pool when the Class is loaded into the method area.

The Java Virtual Machine has strict rules on the format of each part of a Class file (including the constant pool, of course). Each byte must be used to store what data is accepted, loaded, and executed by the VIRTUAL machine. However, the Java Virtual Machine specification does not specify any details about runtime constant pools. Virtual machines implemented by different vendors can implement this memory area according to their needs.

Since the runtime constant pool is part of the method area and is naturally limited by the method area memory, OutOfMemoryError is raised when the constant pool can no longer claim memory.

Code requirements for the capacity of each zone

PC register: The capacity should hold at least one returnAddress or the value of a platform-specific local pointer. (non-adjustable) JVM Stack: The initial capacity can be adjusted, and the maximum and minimum capacity can be adjusted for dynamically expanding and shrinking. Java Heap: Adjustable initial capacity, adjustable maximum and minimum capacity for dynamically expanding and shrinking. Method area: can adjust the initial capacity, for dynamic expansion and contraction, can adjust the maximum and minimum capacity. Local method stack: adjustable initial capacity, adjustable maximum and minimum capacity for dynamically expanding and shrinking.