A deep understanding of one jvm [memory region] and a deep understanding of the jvm Region

Source: Internet
Author: User

A deep understanding of one jvm [memory region] and a deep understanding of the jvm Region

Before the beginning of this article, we need to declare that this series of articles discuss the hot spot VM. Most of the ideas in this article are based on Zhou Zhiming, who deeply understands the Java VM: JVM advanced features and best time. if I have any misunderstanding, please correct me.


Before you start to explore jvm virtual machines, you have to discuss the jvm memory areas:


Program counters

A program counter can also be called a PC register. It may be thought of as a memory area for counting. However, people who know the Assembly will know that, the program technician is actually a register on the CPU, which stores the address of the current instruction execution (or the storage unit of the next instruction ). When the cpu executes this thread, it extracts the address of the current instruction from the program counter, and then automatically adds 1 or points to a command. Run the command in sequence until all the operations are completed.

In a system that supports multiple threads, threads rotate to obtain the cpu execution time. One cpu can only execute one thread, so when rotating threads, make sure that the thread to be rotated can return to the previous state, and the program counter can play this role. When the thread is rotated, the counter records the execution address of the command, you only need to obtain the command to return to the previous status. Obviously, this variable is unique to the thread.

The jvm specification specifies that, when a java method is called, the program counter records the address of the next Virtual Machine bytecode instruction. If the Native method is executed, the value of the program counter is "Undefined ". The memory region is the only region in which the Java Virtual Machine specification does not specify any OutOfMemoryError conditions.

Java Virtual Machine Stack

Stack is a common data structure with advanced features. In jvm, the Java Virtual Machine Stack is a memory model for Java method execution: A Stack Frame (Stack Frame) is created when each Java method is executed to store the local variable table and the operand Stack, dynamic Link, method exit, and other information. Each method, from calling to execution, corresponds to a stack frame's operations on the stack and the stack, so the current method is always at the top of the stack. Speaking of this, I think the number of recursive functions I write will often throw: OverStackOverflowError, because the stack depth has exceeded the maximum stack depth defined by jvm.

In the JVM specification, two types of exceptions are defined for this region:

1. Because the stack is too deep, new stack frames cannot be pushed into the stack, StackOverflowError is thrown.

2. When the stack is dynamically extended, there is no spare memory to allocate to the stack, and an OutOfMemoryError will be thrown.

But if you think about it carefully, there is an intersection between the two. For example, because of the depth of the stack, the request is extended, but there is not enough free space. In this case, both are consistent. Check the relevant blog to know that StackOverflowError will be thrown when it is in a single thread, regardless of the cause of stack failure. In a multi-threaded environment, OutOfMemoryError may be thrown.

Is a virtual machine stack and stack frame concept display:


We can see that a stack frame contains a local variable table, operand stack, dynamic link, method exit, and some additional information. Next we will introduce them one by one:

Local variable table

As the name implies, local variables, such as method parameters, local variables, and returnAdress, can be boolean, byte, char, short, int, float, reference, returnAdress, and long, double type. The basic unit of a local Variable table is Variable Slot. the Java Virtual Machine specification does not explicitly specify the size of a Variable table, but it is very helpful to point out that each table should store boolean, byte, char, short, int, float, reference, returnAdress type, while long and double should have two slots to store their values. For 64-bit data stored with two slots, the virtual machine allocates two slots of continuous space to the data in the high alignment mode.

The Virtual Machine accesses the local variable table by means of index positioning. Its index value starts from 0 until the maximum number of slots in the local variable table. If you access data of 32 bits or less, index n indicates the nth Slot to be accessed. If it is a 64-bit data type, the slots of n and n + 1 are accessed at the same time. One of the two consecutive slots that store 64-bit data types is not allowed. The virtual machine specification explicitly requires that the bytecode sequence for such operations be met, the VM should throw an exception during the class loading phase.

To save stack frame space as much as possible, Slot can be used repeatedly. The scope of the variables defined in the method body does not necessarily cover the whole method body, if the value of the current bytecode PC counter has exceeded the scope of a variable, the Slot occupied by this variable can be allocated to other variables. Of course, it will also be accompanied by some side effects. For example, garbage collection may be affected.

Operand Stack

The operand stack is also called the operation stack. The stack is empty during early method execution on the operand stack. When a method starts to be called, various bytecode commands will write and extract content to and from the operand stack, this corresponds to the stack inbound and outbound operations. The operand stack is the same as a local variable, and boolean, byte, char, short. float, refenrece, and returnAdress are converted to int values for storage, while the 64-bit data type occupies two storage spaces. However, unlike the local operand stack, it does not operate the stored value based on the index, but based on the stack's inbound and outbound operations, because the Java VM commands are from the operand. Stack is not the value in the register, so its operation is based on the operand stack rather than the register.

Dynamic Link

Each stack frame contains a reference pointing to the method to which the stack frame belongs in the constant pool at runtime. This reference is held to support dynamic links during method calling. A large number of symbol references exist in the Class. The method call instruction in the bytecode uses the symbol reference pointing to the method in the constant pool as the parameter. These symbolic references are converted to direct references when the class is loaded or used for the first time. This is called static links. These symbolic references are converted to direct references only at runtime, this is called dynamic link.

Method exit (method exit address)

There are two return methods after a method is called. The first method is to run the bytecode command returned by any method. In this case, the return type in the return command may be installed, and the specified return value will be returned to the previous layer. This method is called the normal completion exit; second, when an exception is thrown and is not captured in time, the method exits. This method is called the exit of exception completion. In this way, no value is returned to the previous layer.

Additional information

The virtual machine specification allows the virtual machine to add information beyond the specification to the stack frame.

Local method Stack

The local method stack is similar to the java Virtual Machine stack function. The difference is that virtual machines serve java methods, while local method stacks serve Native methods, the virtual machine specification has no mandatory requirements for its implementation, so the virtual machine can freely implement it. Even some virtual machines directly combine them with the Virtual Machine stack. It also throws StackOverflowError and OutOfMemeryError exceptions.

Java heap

This is the largest part of VM memory management. What is the specific purpose. First, it is the area where all thread locks are shared. The instances and arrays created in our code are basically allocated in this area, that is, except for the static modified new space, the remaining regions allocated through new are basically allocated here.

This area is the main area for managing the Garbage Collector. Therefore, it is often called the Garbage Collection Heap ). From the perspective of recycling, it will also be divided into two generations: the new generation and the old generation. The new generation can also be subdivided into an Eden and two vor regions. From the perspective of memory allocation, the Java heap can also divide the private buffer allocated to a thread.

The virtual machine specification stipulates that the Java heap can be in a non-consecutive physical memory space, but it only needs to be logically continuous. Of course, its size can be dynamically adjusted (through-Xmx and-Xms ). When there is not enough memory for instance allocation and the heap cannot be expanded, an OutOfMemoryError error will be thrown.

Method Area

The method area is also the area for thread sharing. It is used to store information about classes, constants, static constants, and compiled code loaded by virtual machines. In the virtual machine specification, it is divided into a region with the java heap, but it has a Non-heap (Non-heap) Name. It is also a space that can be dynamically allocated (through-XX: MaxPerSize and-XX: PerSize). It can also be managed by the garbage collection manager like a Java heap, however, it is much more complex and demanding, because of various restrictions, its memory recovery efficiency is very low.

Runtime constant pool

It is part of the Method Area and stores various literal and symbolic references during compilation. This part of content is stored in the class loaded into the method area runtime pool. The content in the constant pool can be added during running. For example, you can use the intern () of the String class to add a String. Therefore, it has an important feature: dynamic. When it cannot apply for memory, it will throw: OutOfMemoryError.

Direct Memory

Direct Memory is not part of the data area during VM running hours, nor is it the memory area defined in the Java Virtual Machine specification.

The NIO (New Input/Output) class is added to jdk1.4, and an I/O Method Based on Channel and Buffer is introduced, it can directly use the Native function library to directly allocate off-heap memory, and then use a DirectByteBuffer object stored in the Java heap as a reference to this memory for operations, which can significantly improve performance in some scenarios, this avoids back-and-forth replication in the Java heap and Native heap. An OutOfMemoryError is thrown when the memory is not allocated enough due to dynamic expansion. (This is mainly from "Understanding Java Virtual Machine version 2").

This is the most basic understanding of jvm and the basis for understanding jvm.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.