The JVM family is finished: The full outline is shown below:
JVM family directories:
- LCODER JVM Series: Runtime Data area
- LCODER JVM series: Class file structure
- LCODER JVM series: Virtual machine class loading mechanism
- LCODER’s JVM series: Garbage collection strategies for JVMS
- LCODER JVM series: bytecode execution engines
Outline of this paper:
What is the JVM
The FULL name of JVM is Java Virtual Machine, also known as Java Virtual Machine. It recognizes files with a.class suffix and can parse its instructions, eventually calling functions on the operating system to do what we want.
JVM execution process:
Helloworld.java is compiled by javac into HelloWorld.class. The class file is loaded into the runtime data area (JVM managed memory) by the Java ClassLoader and interpreted by the execution engine. The JOB of the JVM is to interpret the Class file into machine code that the machine can recognize, and the interpretation execution is bytecode and machine code,
Runtime data area
Definition 1.
During the execution of Java programs, a Java VIRTUAL machine divides the memory managed by the virtual machine into different data areas.
Classification of 2.
These different data areas are divided into: virtual machine stack, local method stack, program counter, method area, and heap. The first three areas are thread private areas, and the last two areas are data areas shared by all threads.
2.1 Program counter:
2.1.1 definition
The address of the instruction pointing to the bytecode being executed by the current thread.
2.1.2 Why is a program counter needed? (Time slice rotation mechanism)
Because Java virtual machine multithreading is implemented by the way threads alternate and allocate processor execution time, at any given time, one processor, or one core of a multi-core processor, will execute instructions in only one thread. Therefore, in order for the thread to switch back to the correct execution position, each thread needs a separate program counter. The counters between the threads do not affect each other and are stored independently. Therefore, the program counter must be thread private.
2.1.3 Why is the program counter the only area of the JVM that is not OOM?
A program counter is a small memory area that only needs to record the address at which the program is running. An int is sufficient.
2.2 VM Stack:
2.2.1 definition
Stores data, instructions, and return addresses required by the current thread to run the method.
The stack data model is characterized by first in, last out, last in, first out. The virtual stack is no exception. At the same time of execution of each method in Java, a stack frame is created, which stores local variable table, operand stack, dynamic link, method exit light information. Each method call to the end of the process, corresponding to a stack frame in the virtual machine stack to the process. If the virtual machine stack is compared to a bullet clip, then the stack frame is the bullet.
2.2.2 Local variation scale
2.2.2.1 definition
The local variable table is the place where various local variables are stored during the execution of the method.
There are only eight basic types, reference types, and returnAddress types that can be stored in a local variable table. The reference type is either a reference pointer to the starting address of the object or a handle to represent the object. The returnAddress type refers to the address of a bytecode instruction. When the method with the return value completes, the method is pushed out of the stack. The address of the stack is remembered using this value. Generally, it is on the next line of the method. 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.
2.2.2.2 Exception Handling
The Java Virtual Machine specification specifies two exception conditions for this area: StackOverflowError and OutOfMemoryError. StackOverflowError is raised if the stack depth of the thread request is greater than the stack depth of the virtual machine. If the virtual stack can scale dynamically, OutOfMemoryError is raised if sufficient memory cannot be allocated during the scaling.
2.2.2.3 How does stack frame work when the method is executed?
public class Person{ public int work(){ int x = 1; int y = 2; int z = (x+y)*10; return z; } public static void main(String[] args){ Person person = new Person(); person.work(); }}Copy the code
This code is compiled using Javac, resulting in the Person.class file, disassembled using Javap -C, resulting in the following code:Analyze how memory changes in the virtual machine stack as this code executes. Execution process:
- Execute main(), and the main() frame is pushed onto the stack
- The work() stack frame pushes the main() stack frame to the bottom
- Int x = 1 in work();
- Int y = 2 in work();
Int z = (x+y)*10; After execution, the operand stack clears
6 Finally, 11: ilOAD_3 12: iRETURN pushes the subscript 3 value of the local variable table into the operand stack as a return
This is how memory changes in the virtual stack when work() is executed
JVM instruction set can refer to the Java VIRTUAL machine JVM bytecode instruction set bytecode opcode instruction classification usage mnemonic
2.3 Local method stack
The role of the Native method stack is very similar to that of the virtual machine stack, except that the virtual machine stack is used to manage calls to Java methods, while the Native method stack is used to manage calls to Native methods. The local method stack is very similar to the virtual machine stack. The virtual machine specification does not specify the language, usage mode, and data structure of the methods, so each virtual machine can implement it freely. HotSpot virtual machine, which directly combines the local method stack with the virtual machine stack.
2.4 method area
The method area is used to store 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. Is an area shared by all threads.
When a class is loaded (loading, validating, preparing, parsing, and initializing), the JVM loads a class file first. The class file contains a constant pool of information that is used to store the version, fields, methods, and interfaces of the class. Various literal and symbolic references generated.
When a class is loaded into memory, the JVM stores the contents of the class file constant pool into the runtime constant pool. During the parsing phase, the JVM replaces symbolic references with direct references (the index value of the object). The run-time constant pool is globally shared, with multiple classes sharing a run-time constant pool. The class file contains only one copy of the same string in the constant pool at run time. This section is explained in detail in the Class file structure below.
Prior to JDK1.7, in the HotSpot virtual machine, the method area was implemented using persistent generations. The advantage of this is that HotSpot’s garbage collector can manage this part of memory as well as the Java heap, eliminating the need to write memory-management code for the method area, but this can lead to other problems: 1. The data in the permanent generation is very inefficient to recycle, but the heap is filled with objects and arrays, and it is the data that needs to be recycled frequently. If the same as in the heap garbage recycling, is undoubtedly a waste of resources; The permanent generation is divided from the Java heap, and its size is still subject to the size of the heap. It cannot be reclaimed for a long time. This area is prone to memory overflow. The pool of static variables and runtime constants for the permanent generation has been moved to the heap. After JDK1.8, the permanent generation in the method area was removed and replaced with a meta-space, which is stored in machine memory and is no longer limited to the Size of the Java heap. This will solve the problem of permanent generation memory overflow.
2.5 the heap
The Java heap is the largest chunk of memory managed by the JVM. An area of memory that is shared by all threads. It is created when a virtual machine is started. The sole purpose of this area of memory is to hold object instances and arrays.
In addition, the Java heap is also the main area of garbage collector management. As objects are created, the heap space becomes more and more occupied, and objects that are no longer used need to be collected irregularly. From the point of view of memory reclamation, the current collector basically adopts generation algorithm, so the Java heap can be subdivided into the new generation and the old age, and the new generation is divided into Eden area, From Survivor area, To Survivor area.
According to the Java Virtual Machine specification, the Java heap can be in a physically discontinuous memory space, as long as it is logically contiguous.
Heap size parameter:
The parameter name | meaning |
---|---|
-Xms | The minimum value of the heap |
-Xmx | Maximum heap size |
-Xmn | Cenozoic size |
-XX:NewSize | Cenozoic minimum |
-XX:MaxNewSize | Cenozoic maximum |
2.6 Use the HSDB tool to drill down into the run-time data area
HSDB is the JDK’s Hotspot Debuger tool, which allows you to view the status of running Java objects in memory, such as oops, class information, thread stack information, heap information, method bytecode and JIT compiled assembly code.
Perform memory analysis on the following code
public class Test { public final static String MAN_TYPE = "man"; public static String WOMAN_TYPE = "woman"; public static void main(String[] args)throws Exception{ Person p1 = new Person(); p1.name = "niuniu"; p1.age = 18; p1.sex = MAN_TYPE; For (int I = 0; i<15; i++){ System.gc(); } Person p2 = new Person(); p2.name = "yangyang"; p2.age = 19; p2.sex = WOMAN_TYPE; Thread.sleep(Integer.MAX_VALUE); } } class Person{ String name; String sex; int age; }Copy the code
2.6.1 open HSDB
If HSDB is used, the first step must be to copy sawindbg. DLL to the corresponding directory of the JRE, otherwise when running HSDB, the error will be reported:
Copy it to the bin directory of the JRE in the Java directory, which on my computer is C:\Program Files\Java\jre1.8.0_271\bin
Step 2: In CMD, open the directory where sa-jdi.jar is located and use the command, Java -cp.\ sa-jdi.jar sun.jvm.hotspot.hsdb to open the HSDB tool.
2.6.2 Adding processes to the HSDB
Use JPS to find the process you want to add
As you can see, 2732 is the process number we are looking for. Add 2732 to the HDSB.
Step 1: Select File -> Attach to HotSpot Process
Step 2: Enter the process number 2732 in the dialog box that pops upYou can then see the thread you are looking for, main
2.6.3 Analyzing memory distribution in the stack
Click the Stack Memory button as shownThe upper part is the stack frame of Sleep method, and the lower part is the stack frame of Main method. The data similar to 0x000000008143DFE0 is the address of stack memory.Zoom in on the Main stack frame
2.6.4 Analyzing memory allocation in the heap
First, to see how the Heap area is allocated in memory, click on Tools-> Heap Parameters in HSDB to get what is shown below.Among them, PSYoungGen (young generation) and PSOldGen (old generation) have three districts in the young generation, namely Eden District, from District and to District. According to the above figure, we can summarize the distribution of memory as shown in the following table: the three regions of the young generation are in a contiguous memory.
Memory address | |
---|---|
Young Generation Eden District | 0x00000000d5c00000 – 0x00000000d7c80000 |
Young generation from area | 0x00000000d7c80000 – 0x00000000d8180000 |
Young generation to area | 0x00000000d8180000 – 0x00000000d8680000 |
Old generation | 0x0000000081400000 – 0x0000000086980000 |
Then let’s look at where the two Person objects in the above code are in the heap. Click on Tools -> Object Histogram from the HSDB tool in sequence to find the Person classDouble-click the Person class to get details for both PersonsThe first Person object with the name “yangyang” and the address is 0x00000000D5C00000. According to the comparison, this Person object is located in the Eden area of the young generation of the heap. According to the memory reclamation mechanism (explained below), the newly created object, Located in Eden District of young Generation. The second Person object with name “niuniu” and address 0x00000000814199d0 is in the old age of the heap. According to the memory reclamation mechanism, objects that have been reclaimed 15 times are in the old age of the heap if they still hold strong references.