Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of Java Virtual Machine Stack and memory Model

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "Java virtual machine stack and memory model case analysis", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "Java virtual machine stack and memory model instance analysis"!

1. Understand Java virtual machine stack and stack frame with bytecode instructions.

Stack frame: each stack frame corresponds to a called method, which can be understood as the running space of a method.

Each stack frame includes a local variable table (Local Variables), Operand stack (Operand Stack), a reference to the runtime pool (A reference to the run-time constant pool), a method return address (Return Address), and additional information.

Local variable table: the local variables defined in the method and the parameters of the method are stored in this table. The variables in the local variable table cannot be used directly. If necessary, they must be loaded into the Operand stack through relevant instructions and used as operands.

Operand stack: storing operands by pressing and leaving the stack.

Dynamic linking: each stack frame contains a reference to the method to which the stack frame belongs in the runtime constant pool, which is held to support dynamic linking (Dynamic Linking) during method invocation.

Method return address: when a method starts execution, there are only two ways to exit, one is to encounter the bytecode instruction returned by the method, and the other is to encounter an exception that is not handled in the method body.

Class Person {private String name= "Jack"; private int age; private final double salary=100; private static String address; private final static String hobby= "Programming"; public void say () {System.out.println ("person say...");} public static int calc (int op1,int op2) {op1=3; int result=op1+op2; return result } public static void order () {} public static void main (String [] args) {calc (1 Person.java 2); order ();}} Compiled from "Person.java" class Person {... Public static int calc (int, int) Code: 0: iconst_3 / / push int type constant 3 into [Operand stack] 1: istore_0 / / store int type value in [local variable 0] 2: iload_0 / / load int type value into stack 3: iload_1 / / load int type value into stack 4: iadd / / pop up the top element of the stack from [local variable 1] The addition of int type is performed, and the result is put into the stack [For example, the iadd instruction (§iadd) adds two int values together. It requires that the int values to be added be the top two values of the operand stack, pushed there by previous instructions. Both of the int values are popped from the operand stack. They are added, and their sum is pushed back onto the operand stack. Subcomputations may be nested on the operand stack, resulting in values that can be used by the encompassing computation.] 5: istore_2 / / Save the int type value at the top of the stack to [local variable 2] 6: iload_2 / / load the int type value from [local variable 2] into the stack 7: ireturn / / return int type data from the method.} 2, in-depth analysis 2.1Stack pointing to the stack

If there is a variable in the stack frame whose type is a reference type, such as Object obj=new Object (), it is typical that the elements in the stack point to objects in the heap.

2.2 method area pointing to the heap

Static variables, constants and other data are stored in the method area. If this is the case, the element in the typical method area points to the object in the heap.

Private static Object obj=new Object (); 2.3heap pointing to the method area

The method area will contain information about the class, and there will be objects in the heap, so how do you know which class created the object?

Think about it: how does an object know which class it was created by? How do you record it? This requires knowing the details of a Java object.

2.4 Java object memory layout

A Java object consists of three parts in memory: object headers, instance data, and alignment padding.

3. Memory model 3.1 diagram

One is a non-stacking area, the other is a stacking area.

The reactor area is divided into two parts, one is Old area, the other is Young area. The Young area is divided into two parts, one is the Survivor region (S0+S1), and the other is the Eden area. Eden:S0:S1=8:1:1 S0 is as big as S1 and can also be called From and To.

As you can see from the previous introduction to Heap, the creation of general objects and arrays allocates memory space in the heap. The key is that there are so many areas in the heap, which area is the creation of that object?

3.2 the area in which the object is created

In general, newly created objects are assigned to the Eden area, and some special large objects are assigned directly to the Old area.

For example, some objects are created in the Eden area, but the memory space in the Eden area must be limited, such as 100m. If 100m has been used or reaches a set critical value, then you need to clean up the Eden memory space, that is, garbage collection (Garbage Collect). Such a GC we call Minor GC,Minor GC refers to the GC of the Young area.

After GC, some objects will be cleaned up, some objects may still be alive, for the living objects need to be copied to the Survivor area, and then empty these objects in the Eden area.

3.3 detailed explanation of Survivor area

As can be seen from the diagram, Survivor is divided into two blocks, S0 and S1, which can also be called From and To. At the same point in time, only one zone of S0 and S1 can have data, and the other is empty.

Then go to the GC above, for example, at first only the Eden area and From have objects, and the To is empty. If you perform a GC operation at this time, the age of the objects in the From area will be + 1. We know that all the living objects in the Eden area will be copied to the To area.

There are two places for surviving objects in the From area.

If the age of the object reaches the previously set age threshold, the object will be moved to the Old area, Eden?From????. Objects that do not reach the threshold are copied to the To area. At this point, the Eden area and the From area have been emptied (the objects that have been GC must be gone, and the objects that have not been GC have their own places).

At this point, From and To switch roles, the former From becomes To, and the former To becomes From. That is, make sure that the Survivor area named To is empty anyway.

Minor GC repeats this process until the To area is filled, and then copies all objects to the old age.

3.4 detailed explanation of Old area

As can be seen from the above analysis, the Old area is generally older objects, or objects that relatively exceed a certain threshold.

There will also be GC operations in the Old area, and the GC in the Old area is called Major GC.

3.5 lifelong understanding of the object

I am an ordinary Java object. I was born in Eden District. I also saw a little brother who looks like me in Eden area. We played in Eden area for a long time. One day there were so many people in Eden that I was forced to go to the "From" area of Survivor District. Since I went to Survivor District, I began to drift, sometimes in the "From" area of Survivor, sometimes in the "To" area of Survivor, without fixed abode. Until I was 18 years old, my father said that I was an adult and that it was time for me to venture into society. So I went to the old generation, there are a lot of people in the old generation, and they are all very old, and I know a lot of people here. In the older generation, I lived for 20 years (every time GC plus one year old), and then I was recycled.

3.6 frequently asked questions

How to understand Minor/Major/Full GC

Minor GC: the new generation

Major GC: the old age

Full GC: the new generation + the old age

Why do I need the Survivor zone? Can't we just have Eden?

If there is no Survivor,Eden area, every time Minor GC is performed, the surviving objects will be sent to the old age. As a result, the old age quickly fills up and triggers Major GC (because Major GC is usually accompanied by Minor GC, which can also be seen as triggering Full GC). The memory space of the old era is much larger than that of the new generation, and a Full GC takes much longer than a Minor GC. What is the harm of long execution time? Frequent Full GC takes a long time and will affect the execution and response speed of large programs.

You might say, then there will be more or less space in the old days. If the space of the old age is increased, more living objects can fill the old age. Although the Full GC frequency is reduced, with the increase of space in the old age, once Full GC occurs, it takes longer to execute.

If the space of the old age is reduced, although the time required for Full GC is reduced, the old age is quickly filled with living objects, and the frequency of Full GC increases.

Therefore, the significance of the existence of Survivor is to reduce the number of objects sent to the old age, and then reduce the occurrence of Full GC. The pre-screening of Survivor ensures that only those objects who can survive in the new generation after 16 times of Minor GC will be sent to the old age.

Why do I need two Survivor zones?

The biggest advantage is to solve the fragmentation. In other words, why not a Survivor area? In the first part, we learned that the Survivor zone must be set. Assuming that there is only one Survivor zone, let's simulate the process:

The newly created object is in the Eden, and once the Eden is full, the living object in the Minor GC,Eden will be moved to the Survivor area. This continues, and the next time the Eden is full, the problem arises. There are some living objects in Minor GC,Eden and Survivor. If the surviving objects in the Eden area are rigidly placed in the Survivor area, it is obvious that the memory occupied by the two objects is discontinuous, which leads to memory fragmentation.

There is always one Survivor space that is empty and another Survivor space that is not empty without fragments.

Why is the Eden:S1:S2 8:1:1 in the new generation?

Available memory in the new generation: 9:1 memory guaranteed by the replication algorithm

The Eden:S1 area in the available memory is 8:1

That is, Eden:S1:S2 = 8:1:1 in the Cenozoic era.

4. Verify 4.1 heap memory overflow

Program:

@ RestControllerpublic class HeapController {List list=new ArrayList (); @ GetMapping ("/ heap") public String heap () throws Exception {while (true) {list.add (new Person ()); Thread.sleep (1);}

Remember to set parameters such as-Xmx20M-Xms20M

Running result:

Exception in thread "http-nio-8080-exec-2" java.lang.OutOfMemoryError: GC overhead limit exceeded4.2 method area memory overflow

For example, add Class information to the method area

4.2.1 asm dependency and Class code asm asm 3.3.1public class MyMetaspace extends ClassLoader {public static List > classes = new ArrayList exampleClass = test.defineClass ("Class" + I, code, 0, code.length); classes.add (exampleClass);} return classes;}} 4.2.2 Code @ RestControllerpublic class NonHeapController {List > () @ GetMapping ("/ nonheap") public String nonheap () throws Exception {while (true) {list.addAll (MyMetaspace.createClasses ()); Thread.sleep (5);}

Set the size of Metaspace, such as-XX:MetaspaceSize=50M-XX:MaxMetaspaceSize=50M

Running result:

Java.lang.OutOfMemoryError: Metaspaceat java.lang.ClassLoader.defineClass1 (Native Method) ~ [na:1.8.0_191] at java.lang.ClassLoader.defineClass (ClassLoader.java:763) ~ [na:1.8.0_191] 4.3 Virtual Machine Stack 4.3.1 Code demonstration StackOverFlowpublic class StackDemo {public static long count=0; public static void method (long I) {System.out.println (count++); method (I) } public static void main (String [] args) {method (1);}} 4.3.2 understanding and explanation

Stack Space is used to press the Stack Frame (stack frame) into the recursive call to the method. So when the recursive call is too deep, it is possible to run out of Stack Space and expose StackOverflow errors.

-Xss128k: sets the stack size for each thread. The stack size of each thread after JDK 5 is 1m, compared with 256K per thread before. Adjust according to the amount of memory required by the applied thread. Decreasing this value generates more threads under the same physical memory. However, the operating system still has a limit on the number of threads in a process, which cannot be generated indefinitely, and the experience value is about 3000 to 5000.

The size of the thread stack is a double-edged sword. If the setting is too small, the stack overflow may occur, especially when there is a recursive and large loop in the thread. If the value is set too high, it will affect the number of stacks created. If it is a multi-threaded application, a memory overflow error will occur.

At this point, I believe you have a deeper understanding of "Java virtual machine stack and memory model instance analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report