Secrets of Java's JVM

Copyright statement: This article is reproduced. The copyright of the source main article follows the CC 4.0 BY-SA copyright agreement. Please attach the link to the source of the original text and this statement.
Link to this article: https://blog.csdn.net/wo541075754/article/details/102623406

For developers, if they don't understand Java's JVM, it is really difficult to write good code and find good bugs. At the same time, JVM is also the worst-hit area in the interview session. Beginning today, the "JVM Detailed" series is launched, which will take you to an in-depth understanding of JVM related knowledge.

We can't interview for the interview, but you will definitely become the "brightest star" in the interview and the job if you learn these core knowledge. This series was first published on the WeChat public account "New Vision of Programs". Next, open our first article "Detailed Explanation of JVM Memory Structure".

Learning methods are also important. In this series of learning process, we will guide everyone to learn through the "Feynman Learning Method", and try to use pictures and texts to explain. As the saying goes, a picture is worth a thousand words.
think for a while

To learn a piece of knowledge, you should know why you learn it. Some people will say that these writing codes don't seem to be necessary. It seems that JVM has done everything for us. Then, think about why you should learn the structure of the JVM virtual machine.

Have you encountered such confusion: how much heap memory should be set? How exactly caused the OutOfMemoryError exception? How to tune the JVM? How about garbage collection of JVM? What did the JVM do even to create a String object?

These questions will slowly be answered as the learning progresses, and the first step to solve these problems is to understand the composition of the JVM.
JVM memory structure

The java virtual machine divides the memory into different data areas during the execution of the program. Take a look at the figure below.

image

If you understand the above figure, you basically have half of the memory structure of the JVM. What can we see from the picture above? The layman looks at the excitement, the insider looks at the doorway. The following information can be obtained from the figure.

First, JVM is divided into five areas: virtual machine stack, local method stack, method area, heap, and program counter. PS: Don’t reject English. Memorizing in English here makes it easier to understand.

Second, the virtual machine stack, local method stack, and program counter in the five areas of the JVM are thread-private, and the method area and heap are shared by the thread. The figure has been distinguished by color, green means "passing", orange means stop for one stop (need to wait).

Third, different areas of the JVM occupy different memory sizes. Generally, the heap is the largest and the program counter is smaller. So what will be placed in the largest area? Of course, it is the most "object" in Java.

Learning extension: If you remember this picture, can you tell about the memory structure of the JVM? You can give it a try, remember not to memorize it, and use your imagination.
Heap

It has been concluded that the heap memory is the largest, the heap is shared by threads, and the purpose of the heap is to store objects. Almost all object instances are allocated here. Of course, as optimization techniques are updated, some data will also be placed on the stack and so on.

The gun shot the bird and the tree caught the wind. Because the heap occupies the largest memory space, the heap is also the main area (key object) of Java garbage collection, so it is also called "GC heap" (Garbage Collected Heap).

Regarding the operation of GC, we will talk in detail in the following chapters, but because of the existence of GC, modern collectors basically use generational collection algorithms, and the heap has been refined.

image

Similarly, a summary analysis of the content presented in the above figure.

First, the GC operation of the heap adopts the generational collection algorithm.

Second, the heap distinguishes the young generation and the old generation;

Third, the new generation is divided into: Eden space, From Survivor (S0) space, and To Survivor (S1) space.

The Java virtual machine specification stipulates that the Java heap can be in a physically discontinuous memory space, as long as it is logically continuous. That is to say, the memory of the heap is pieced together piece by piece. To increase the heap space, just "patch together" (scalability), but when there is no memory in the heap to complete the instance allocation, and the heap can no longer be expanded, an OutOfMemoryError exception will be thrown.
Method Area

The method area and the heap have many commonalities: thread sharing, memory discontinuity, scalability, garbage collection, and also throws an OutOfMemoryError exception when it cannot be extended.

Because of this similarity, the Java virtual machine specification describes the method area as a logical part of the heap, but it is currently separated from the Java heap (Non-Heap).

The personalization of the method area is that it stores data such as class information, constants, static variables, and code compiled by the just-in-time compiler that have been loaded by the virtual machine.

The memory recovery goal of the method area is mainly for the recovery of the constant pool and the unloading of the types. Generally speaking, the recovery "score" of this area is more difficult to satisfy, especially the unloading of the types. The conditions are quite harsh, but the recovery does have. necessary.

image
Program Counter Register

Regarding the program counter, we have already learned that it takes up a small amount of memory and is readily available and private. It is the only area where there is no OutOfMemoryError.

The function of the program counter can be regarded as the line number indicator of the bytecode executed by the current thread. When the bytecode interpreter works, it selects the next bytecode instruction by changing the value of the counter. Among them, basic functions such as branching, looping, jumping, exception handling, and thread recovery all need to rely on counters to complete.

The multi-threading of the Java virtual machine is realized by the way that threads alternately switch and allocate processor execution time. At any certain moment, a processor (a core for a multi-core processor) will only execute in one thread Instructions.

image

Therefore, in order to restore to the correct execution position after thread switching, each thread needs to have an independent program counter. The counters between the threads do not affect each other and are stored independently. We call this type of memory area "thread private "Memory.

If the thread is executing a Java method, this counter records the address of the executing virtual machine bytecode instruction; if the thread is executing a Natvie method, the counter value is empty (Undefined).
Virtual machine stack (JVM Stacks)

The virtual machine stack thread is private, and its life cycle is the same as that of the thread.

A stack frame is a data structure used to support method calls and method execution by a virtual machine. The stack frame stores the method's local variable table, operand stack, dynamic connection and method return address and other information. The process of each method from invocation to completion of execution corresponds to the process of a stack frame in the virtual machine stack from pushing to popping.

image

Local Variable Table (Local Variable Table) is a set of variable value storage space used to store method parameters and local variables defined in the method. Including 8 basic data types, object references (reference types) and returnAddress types (pointing to the address of a bytecode instruction).

The 64-bit long and double data will occupy two local variable spaces (Slot), and the remaining data types will only occupy one.

If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, a StackOverflowError exception will be thrown; if the virtual machine stack is dynamically expanded, it will throw an OutOfMemoryError exception when it cannot apply for enough memory.

Operand stack (Operand Stack) is also called operation stack, which is a last in first out stack (LIFO). As the method is executed and the bytecode instruction is executed, constants or variables are copied from the fields of the local variable table or object instance and written to the operand stack, and then the elements in the stack are popped to the local variable table as the calculation proceeds. Or return to the method caller, that is, pop/push operations.

Dynamic linking: In the Java virtual machine stack, each stack frame contains a symbolic reference pointing to the method to which the stack belongs in the runtime constant pool. The purpose of holding this reference is to support dynamic linking during method calls (Dynamic Linking) .

Method return: No matter whether the method is completed normally or not, you need to return to the place where the method was called before the program can continue.
Native Method Stacks

Native Method Stacks are similar to virtual machine stacks, and they also throw StackOverflowError and OutOfMemoryError exceptions.

The difference is that the virtual machine stack serves the virtual machine to execute Java methods (bytecode), while the local method stack serves the native methods used by the virtual machine.
summary

After the above explanation, everyone must have understood the basic situation of the JVM memory structure. Let's compare the mind map to summarize and see how much you can tell.

image

For more content in the "JVM Detailed Explanation" series and other interview questions series, please pay attention to the WeChat public account "New Vision of Programs", which will be continuously updated.

Original link: "Detailed Explanation of JVM Memory Structure"

Series of articles: "Interviewer, don't ask me "Java GC garbage collection mechanism" anymore"
————————————————
Copyright statement: This article is the CSDN blogger "Second Brother-Public Account" -The original article of "New Vision of Program" follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/wo541075754/article/details/102623406

Guess you like

Origin blog.csdn.net/ccpit2b2c/article/details/102719751