Home  >  Article  >  Java  >  Example analysis of memory allocation and recycling strategies in Java virtual machine

Example analysis of memory allocation and recycling strategies in Java virtual machine

PHPz
PHPzforward
2023-05-02 10:22:121305browse

Memory allocation and recycling strategy

The most fundamental goal of the automatic memory management of the Java technology system is to automatically solve two problems: automatically allocating memory to objects and automatically recycling the memory allocated to objects.

1. Overview

The memory allocation of objects, conceptually, should be allocated on the heap (in fact, it may also be disassembled into scalar types after just-in-time compilation and indirectly allocated on the stack). Under the classic generation design, new objects are usually allocated in the young generation. In rare cases (for example, the object size exceeds a certain threshold), they may also be allocated directly in the old generation. The rules for object allocation are not fixed. The "Java Virtual Machine Specification" does not stipulate the creation and storage details of new objects. This depends on which garbage collector the virtual machine is currently using and the memory-related functions in the virtual machine. Parameter settings.

(1) Objects are allocated in Eden first

In most cases, objects are allocated in the new generation Eden area. When the Eden area does not have enough space for allocation, the virtual machine will initiate a Minor GC.

1. When there is enough space in the Eden area

Virtual machine parameters

-verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8

Parameter description

Try to allocate three 2MB size and one 4MB size Object, at runtime, the Java heap size is limited to 20MB through the three parameters -Xms20M, -Xmx20M, and -Xmn10M, which is not expandable. 10MB is allocated to the new generation, and the remaining 10MB is allocated to the old generation. -XX: Survivor-Ratio=8 determines that the space ratio between the Eden area and a Survivor area in the new generation is 8:1.

package com.xiao.test.Test;

public class test {
    private static final int _1MB = 1024 * 1024;
    public static void main(String[] args) {
        byte[] byte1,byte2,byte3;
        byte1 = new byte[2 * _1MB];
        byte2 = new byte[2 * _1MB];
        byte3 = new byte[2 * _1MB];   
    }
}

Example analysis of memory allocation and recycling strategies in Java virtual machine

2. When the Eden area does not have enough space

The virtual machine parameters are the same

package com.xiao.test.Test;

public class test {
    private static final int _1MB = 1024 * 1024;
    public static void main(String[] args) {
        byte[] byte1,byte2,byte3,byte4;
        byte1 = new byte[2 * _1MB];
        byte2 = new byte[2 * _1MB];
        byte3 = new byte[2 * _1MB];
        byte4 = new byte[3 * _1MB];
    }
}

Example analysis of memory allocation and recycling strategies in Java virtual machine

Obviously Minor GC

(2), large objects directly enter the old generation

1. What is a large object?

Large objects refer to Java objects that require a large amount of continuous memory space. The most typical large objects are long strings or arrays with a large number of elements.

2. Reasons why large objects should be avoided in Java virtual machines

When allocating space, it can easily cause garbage collection to be triggered in advance when there is obviously a lot of space in the memory to obtain enough space. Only continuous space can be used to place them. When copying objects, large objects mean high memory copy overhead.

3. The advantage of large objects entering the old generation directly

Avoid copying back and forth between the Eden area and the two Survivor areas, resulting in a large number of memory copy operations (HotSpot virtual machine provides -XX : PretenureSizeThreshold parameter, specifying that objects larger than the set value are directly allocated in the old generation).

(3) Long-term surviving objects will enter the old generation

1. How does the virtual machine determine whether the object is long-term surviving?

When recycling memory, it must be able to decide which surviving objects should be placed in the new generation and which surviving objects should be placed in the old generation. To do this, the virtual machine defines an object age (Age) counter for each object, which is stored in the object header.

2. The process of object age increase and promotion to the old generation

Objects are usually born in the Eden area. If they still survive after the first Minor GC and can be accommodated by the Survivor, the object will The object will be moved to the Survivor space and its object age will be set to 1 year old. Every time an object survives a Minor GC in the Survivor area, its age increases by 1 year. When its age reaches a certain level (default is 15), it will be promoted to the old generation. The age threshold for an object to be promoted to the old generation can be set through the parameter -XX: MaxTenuringThreshold.

3. The reason why long-lived objects will enter the old generation

We all know that the garbage collection algorithm of the new generation is a mark-copy algorithm. If long-lived objects are still stored in the new generation If so, it will bring about the problem of increased copy overhead. Therefore, we put objects larger than a certain age threshold into the old generation, which can reduce the pressure on the new generation during garbage collection.

(4) Dynamic object age determination

In order to better adapt to the memory conditions of different programs, the HotSpot virtual machine does not always require that the age of the object must reach -XX:MaxTenuringThreshold before it can be promoted. In the old generation, if the sum of the sizes of all objects of the same age in the Survivor space is greater than half of the Survivor space, objects whose age is greater than or equal to this age can directly enter the old generation without waiting for the age required in -XX:MaxTenuringThreshold.

(5), Space Allocation Guarantee

1. Contents of Space Allocation Guarantee

Before Minor GC occurs, the virtual machine must first check whether the maximum available continuous space in the old generation is greater than the total space of all objects in the new generation. If this condition is true, then this time Minor GC can ensure safety. If it is not established, the virtual machine will first check whether the setting value of the -XX: HandlePromotionFailure parameter allows guarantee failure; if it is allowed, it will continue to check whether the maximum available continuous space in the old generation is greater than the average size of objects promoted to the old generation. If it is greater, A Minor GC will be attempted, although this time the Minor GC is risky; if it is less than, or the -XX: HandlePromotionFailure setting does not allow risk, then a Full GC will be performed instead.

2. What is the risk of "adventure"?

As mentioned earlier, the new generation uses the copy collection algorithm, but for the sake of memory utilization, only one of the Survivor spaces is used as a rotating backup. , so when a large number of objects still survive after Minor GC - the most extreme case is that all objects in the new generation survive after memory recycling, the old generation needs to perform allocation guarantees, and objects that cannot be accommodated by the Survivor are directly sent to the old generation. , which is similar to loan guarantees in life. To make such a guarantee in the old generation, the premise is that the old generation itself still has remaining space to accommodate these objects. However, how many objects will survive this recycling cannot be clearly known before the actual memory recycling is completed, so we can only take The average size of the object capacity promoted to the old generation in each previous recycling is used as an experience value. It is compared with the remaining space in the old generation to decide whether to perform Full GC to free up more space in the old generation.

3. Do we need to open the guarantee?

Taking the historical average for comparison is actually still a solution based on betting on probability. That is to say, if the number of objects after a certain Minor GC survives suddenly increases, which is much higher than the historical average, it will still lead to Guarantee failed. If there is a guarantee failure, then you have to re-initiate Full GC honestly, so the pause time will be very long. Although the circle is the largest when the guarantee fails, the -XX: HandlePromotionFailure switch is usually turned on to avoid Full GC being too frequent.

The above is the detailed content of Example analysis of memory allocation and recycling strategies in Java virtual machine. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete