当前位置:网站首页>Garbage collector and memory allocation strategy

Garbage collector and memory allocation strategy

2022-04-23 19:20:00 Xuanguo Guo

Catalog

Garbage collector and memory allocation strategy

One 、 How to judge whether an object is alive or not

1、 Reference counting algorithm

2、 Reachability analysis algorithm

3、 Is the object dead ?

Two 、 Garbage collector algorithm

1、 Generational collection theory

2、 Mark - Clear algorithm

3、 Mark - Copy algorithm

4、 Mark - Sorting algorithm

5、 Safe points and safe areas

3、 ... and 、 Garbage collector

1、Serial The collector

2、ParNew The collector

3、Parallel Scavenge The collector

4、CMS The collector

5、Garbage First The collector

6、ZGC The collector

7、 How to choose a garbage collector

8、GC Log view

Four 、 Memory allocation and recycling strategy

1、 Priority is given to Eden Distribute

2、 Large objects go directly into the old generation

3、 Long term survivors will enter the old age

4、 Dynamic object age determination

5、 Space allocation guarantee


Garbage collector and memory allocation strategy

For our Java For the programmer , garbage collection ? We never deal with garbage collection when we write code , And the program runs very stably .
That's because of our jvm The virtual machine has helped us get rid of those useless garbage objects , There is no need for us programmers to deal with those garbage objects .
imagine , If the object we created in the program is not destroyed , Our memory is so big , Then the memory will soon be full , The program can't continue to run , This obviously won't work .
So here's the problem ,Java The program will create a large number of objects ,jvm How do virtual machines know which ones are still in use , What can be destroyed ?
So let's take a look at jvm How do virtual machines recognize which objects are useless objects , To be destroyed , Which objects have to remain , After destroying the corresponding useless objects , How to deal with the subsequent memory allocation .

 

One 、 How to judge whether an object is alive or not

1、 Reference counting algorithm

Add a reference counter to the object , Whenever there is a place to reference this object , This counter adds one , When this reference fails , Just subtract one from the counter , It is impossible to use any object whose counter is zero at any time .
This algorithm is simple , It's very efficient , But mainstream java Virtual machines don't use this algorithm to manage memory , Because there are many exceptions to this algorithm to consider , It requires a lot of extra processing to ensure correct work , For example, the case of mutual circular reference cannot be solved directly by this algorithm .
According to this example , except gc1 and gc2 Cross reference , There are no references behind , In fact, both objects can no longer be accessed , But because of cross references , Cause the counter to be non-zero , Then the reference counting algorithm cannot recycle them .
7097K->3000K(15872K) It can be seen from the log that , Yes 4M Memory was freed up , It also explains Java Virtual machines do not use reference counting algorithms to determine whether objects survive .

Code example :

/**
 * @ClassName ReferenceGC
 * @Author chenxuan
 */
public class ReferenceGC {

    public Object instance = null;

    private static final int _1MB = 1024 * 1024;
    // Occupy memory , What can be seen in the log is relatively clear 
    private byte[] bytes = new byte[2 * _1MB];

    /**
     * gc Look at the newly created gc1 and gc2 Is it recycled 
     * @Author chenxuan
     **/
    public void test(){
        ReferenceGC gc1 = new ReferenceGC();
        ReferenceGC gc2 = new ReferenceGC();

        gc1.instance = gc2;
        gc2.instance = gc1;

        gc1 = null;
        gc2 = null;
        // Simulation occurs gc
        System.gc();
    }

    /**
     * VM Args: -XX:+PrintGCDetails
     *  Print GC Log details 
     * @Author chenxuan
     **/
    public static void main(String[] args) {
        ReferenceGC gc = new ReferenceGC();
        gc.test();
    }
}

Console output :

Connected to the target VM, address: '127.0.0.1:52574', transport: 'socket'
    [GC (Allocation Failure) [DefNew: 4280K->512K(4928K), 0.0012588 secs] 4280K->953K(15872K), 0.0012942 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
    [GC (Allocation Failure) [DefNew: 4694K->0K(4928K), 0.0024762 secs] 5135K->5049K(15872K), 0.0024979 secs] [Times: user=0.00 sys=0.02, real=0.00 secs]
    [Full GC (System.gc()) [Tenured: 5049K->3000K(10944K), 0.0014451 secs] 7097K->3000K(15872K), [Metaspace: 2051K->2051K(4480K)], 0.0014752 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
    Heap
    def new generation   total 4992K, used 179K [0x05200000, 0x05760000, 0x0a750000)
    eden space 4480K,   4% used [0x05200000, 0x0522ce58, 0x05660000)
    from space 512K,   0% used [0x05660000, 0x05660000, 0x056e0000)
    to   space 512K,   0% used [0x056e0000, 0x056e0000, 0x05760000)
    tenured generation   total 10944K, used 3000K [0x0a750000, 0x0b200000, 0x15200000)
    the space 10944K,  27% used [0x0a750000, 0x0aa3e300, 0x0aa3e400, 0x0b200000)
    Metaspace       used 2055K, capacity 2306K, committed 2368K, reserved 4480K
    Disconnected from the target VM, address: '127.0.0.1:52574', transport: 'socket'

 

2、 Reachability analysis algorithm

The idea of this algorithm is through a series called "GC Roots" As the actual node set of , Start with these nodes , Search down by reference , The path taken by the search process is called " References to the chain ", If an object arrives at GC Roots There is no chain of references between , Then this object can no longer be used , The objects that can be recycled .
GC Roots The objects include the following :
1) Objects referenced in the virtual machine stack , For example, the parameters used in the method stack called by each thread , local variable , Temporary variable
2) Objects referenced by class static properties in method area , Such as Java Class reference type static variable
3) In the method area, the constant references the object , Such as references in the string constant pool
4) In the local method stack JNI, For example, the basic data type corresponds to Class object , And the system class loader
5) All are locked in sync (synchronized keyword ) The object of holding
6) reflect Java What's going on inside the virtual machine JMXBean、JVMTI Callback registered in , Local code cache, etc .

Java The concepts of heap reference in are 4 Kind of ,
1) Strong citation : The most traditional quote , Such as Object obj = new Object(); such . In any case , As long as the strong reference relationship is still , The garbage collector will never recycle the referenced objects .
2) Soft citation : It's useful to describe some , But not necessarily , Only objects associated with soft references , Before the system is about to run out of memory , Only then will these objects enter the recycling and return for the second recycling .
3) Weak reference : Describe the unnecessary objects , But it's weaker than soft references . Objects associated with weak references can only survive until the next garbage collection .
4) Virtual reference : The weakest kind of reference relationship . Whether an object has a virtual reference , It doesn't affect their survival time at all , It is also used to obtain an object instance through virtual reference .

 

3、 Is the object dead ?

Even if the current object has been determined as a recyclable object in the reachability analysis algorithm , It's not recycling right away , It just marks , Pass by 2 Secondary marking , Only in this way can we really recycle objects .
The first is the first marking of recyclable objects after filtering by reachability analysis algorithm .
The second is to see if there are overrides in these objects finalize() Method , If there is , Then make the second screening mark , If in finalize() Method to revive the object again , Then the object will not be recycled by the garbage collector .

Code example :

/**
 *  A self rescue before the object is garbage collected  finalize
 * @Author chenxuan
 */
public class FinalizeGC {

    public static FinalizeGC gc = null;

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("execute finalize");
        // Reassign the object , Make it non recyclable 
        FinalizeGC.gc = this;
    }

    public static void main(String[] args) throws InterruptedException {
        gc = new FinalizeGC();

        //gc Set as null, Make the object have no reference chain in the reachability analysis algorithm , Considered recyclable 
        gc = null;
        // Conduct GC
        System.gc();
        // because finalize Method priority is very low , So wait a minute 
        TimeUnit.MILLISECONDS.sleep(500);
        if(gc != null){
            System.out.println("this is alive");
        }else {
            System.out.println("this is dead");
        }

        // Empty again 
        gc = null;
        // Conduct GC
        System.gc();
        // because finalize Method priority is very low , So wait a minute 
        TimeUnit.MILLISECONDS.sleep(500);
        // This time the object is recycled . because finalize Will only be executed once 
        if(gc != null){
            System.out.println("this is alive");
        }else {
            System.out.println("this is dead");
        }
    }
}

Console output

execute finalize
this is alive
this is dead

about finalize() Method , I check the relevant documents , It is not recommended to use , Avoid using ,finalize What you can do try-finally Or other ways to do better 、 More timely .

 

Two 、 Garbage collector algorithm

Just introduced how to judge whether an object should be recycled , Then let's take a look at how virtual machines are recycled

1、 Generational collection theory

 1) Weak generational Hypothesis : Most tree objects are born in the morning and die in the evening .
 2) Strong generational Hypothesis : The more times an object goes through the garbage collection process, the harder it is to recycle .
 3) Cross generational citation Hypothesis : Cross generation references account for only a very small number of references compared to the same generation references .
be based on 1、2 Two hypotheses , So the collector will Java Pile up different areas , That's why we have the well-known Cenozoic (Eden Space ,From Survivor Space ,To Survivor Space ), Old age .
Therefore, there is also the collection and division of corresponding areas , Cenozoic collection ("Minor GC/Young GC", Collect recyclable objects in the Cenozoic ), Old age collection ("Major GC/Old GC", Collect recyclable objects from older generations ,CMS The collector ), Mixed collection ("Mixed GC", Collect recyclable objects of the whole Cenozoic and some old ages ,G1 The collector ), Collect the whole pile ("Full GC", Collect the whole Java Recyclable objects in the heap and method area ).

2、 Mark - Clear algorithm

Mark - The scavenging algorithm is the most basic garbage collection algorithm . There are two stages: marking and clearing , First mark all objects to be recycled , After marking , Recycle all marked objects in a unified way .
shortcoming :
1) The efficiency of execution is not stable , If it contains a large number of objects , Most of them are recyclable objects , At this time, a lot of marking and clearing actions are required , The more objects , Then the lower the efficiency .
2) The problem of memory space fragmentation , Mark - After removal, there will be a large number of discontinuous space debris , The excessive fragmentation of space may lead to the need to allocate large objects during the operation of future programs, which cannot find enough continuous memory and have to trigger another garbage collection action in advance .

3、 Mark - Copy algorithm

Divide the available memory into two equal sized blocks according to its capacity , Use only one piece at a time , When a block of memory runs out , Copy the surviving objects to another piece , Then clean up all the memory space in the previous block .
shortcoming : The cost of this algorithm is to reduce the available memory to half , A great waste of resources .
Because this algorithm is very efficient for the case of a small number of surviving objects , Most of the objects in the young generation are born in the morning and die in the evening , Therefore, it is more suitable for the garbage collection of the younger generation .
By the way, I would like to introduce some common Java The memory layout of the new generation in the heap
Divide the Cenozoic into a larger Eden Space and two smaller ones Survivor Space , Every time you allocate memory, only use Eden And one of them Survivor. What is the reason for garbage collection , take Eden and Survivor Objects that are still alive in are copied to another piece at a time Survivor In space , And clean it up Eden And the one I just used Survivor Space .HotSpot Virtual machine default Eden and Survivor The ratio is 8:1, That is, the memory space available in each Cenozoic is the largest of the whole Cenozoic space 90%, Because there is 2 individual Survivor Space , It happens to be 8:1:1.

4、 Mark - Sorting algorithm

Mark - When the survival rate of the object is high, the replication algorithm , A large number of objects have to be copied every time , Then the efficiency will be reduced , And it's wasteful 50% Space . Like the older generation, almost all objects are non recyclable , Then we have to consider another algorithm .
First mark all objects to be recycled , After marking , Let all living objects move to one end of memory space , Then clean up the memory outside the boundary . Marking and marking - Clear the difference between algorithms , After marking , Before cleaning up, the living objects will be sorted together , Then clean up the remaining space .
shortcoming : Because you need to move living objects , Then, when moving the object, the program pauses for a while , Because if you need to move the object , If I happen to be moving A object , Delete the original space , The program is still working , To get A Object information , Found the original memory A The object is gone , Then the program will report an error at this time , This must not work . This pause application is commonly known as "stop the world".

5、 Safe points and safe areas

The garbage collection algorithm is introduced above . For example, you need to stop the application , Or switch cpu Time slice time , Our program stops at any command , A large amount of storage space will be required to store the corresponding stop position and instructions .
safer : It determines that the user program cannot stop at any position of the code instruction flow to start garbage collection when executing , It's a mandatory requirement that it must be executed before it can be suspended until it reaches a safe point . For example, the position of loop jump , The location of method calls, and so on .
The safety area : Now that you're safe , Why a safe area ? Because sometimes the program can't reach the corresponding safety point in a short time , For example, the thread is in sleep The state or blocked state , At this time, it is impossible to wait for the thread to reach the corresponding safe point , So at this time, we need a safe area to solve this problem .
When a thread executes code into a safe zone , Will mark that you have entered a safe area , So when garbage collection happens during this time , Then you don't have to worry about the threads that have been identified in the safe area . If the thread wants to leave the safe zone , It's still garbage collection , Then it will pause there , Wait for garbage collection to complete before continuing .

 

3、 ... and 、 Garbage collector

1、Serial The collector

Launch parameters :-XX:+UseSerialGC -XX:+UseSerialOldGC
It's a single threaded collector , Not only one thread will be used to complete garbage collection , While he was collecting garbage , All other worker threads must be suspended , Until the end of his collection .
The new generation uses replication algorithms , The old days use signs - Sorting algorithm .
Serial The collector has no overhead of thread interaction , Naturally, high single thread collection efficiency can be achieved .
Serial Old The collector is Serial Old age version of collector , It is also a single-threaded collector . It has two main uses : One use is in JDK1.5 As well as previous versions of the Parallel Scavenge Collector used with , Another use is for CMS The backup plan of the collector .

2、ParNew The collector

Launch parameters :-XX:+UseParNewGC
In essence Serial The multithreaded parallel version of the collector .
The new generation uses replication algorithms , The old days use signs - Sorting algorithm .

3、Parallel Scavenge The collector

Launch parameters :-XX:+UseParallelGC( The younger generation ),-XX:+UseParallelOldGC( Old age )
The goal of the collector is to achieve a controllable throughput . The so-called throughput is the ratio of the time the processor spends running user code to the total time consumed by the processor , namely : throughput = Run code time /( Run code time + Garbage collection time )
Garbage collection pause time parameter :-XX:MaxGCPauseMillis
Throughput size parameter :-XX:GCTimeRatio , The value of this parameter is 0-100 Integer between .
According to different systems , Different memory sizes , Different programs reasonably set parameter values .
The new generation uses replication algorithms , The old days use signs - Sorting algorithm .

4、CMS The collector

CMS(Concurrent Mark Sweep) Collector is a kind of collector that aims at obtaining the shortest recovery pause time .
The whole process is divided into 4 A step
  1) Initial marker : Just mark it GC Roots Objects that can be directly associated with , fast .
  2) Concurrent Tags : from GC Roots The process of traversing the whole object graph begins with the directly related object , This process takes a long time but does not need to pause the user thread , Can run concurrently with the garbage collection thread
  3) Re label : To fix the concurrency flag period , The mark record of the part of the object whose mark changes due to the continuous operation of the program . Because the concurrency flag runs concurrently with the garbage collection thread , Therefore, some objects will be changed
  4) Concurrent elimination : Clean up and delete objects that have been marked as recyclable in the marking stage , Because you don't need to move live objects , Therefore, this stage can also be used concurrently with the user thread
The two steps of initial marking and re marking are still needed stop the world Of .

shortcoming :
  1) In the concurrent phase , Although it doesn't cause user threads to pause , But it will occupy part of the thread and cause the program to slow down , Reduced throughput .
  2) In the concurrent marking and concurrent cleanup steps , The user thread is still running , The program will generate new recyclable garbage objects , This part of the garbage object appears after the tag is re marked , Then in the concurrent cleanup step, the newly generated garbage object will not be recycled , It can only be cleaned up at the next garbage collection . The garbage objects generated during this period are also called floating garbage .
  3) because CMS It's based on markers - Clear the collector implemented by the algorithm , That means a lot of space debris will appear after the collection , When there is too much space debris , Later, the allocation of large objects will bring great difficulties , When there is not enough contiguous space to allocate this large object , It will trigger once Full GC.JDK9 You can go through -XX:CMSFullGCsBeforeCompaction To clean up memory space .

CMS Related core parameters of
1. -XX:+UseConcMarkSweepGC: Enable cms
2. -XX:ConcGCThreads: concurrent GC Number of threads
3. -XX:+UseCMSCompactAtFullCollection:FullGC Then do compression and finishing ( Reduce debris )
4. -XX:CMSFullGCsBeforeCompaction: How many times FullGC Then compress once , The default is 0, For every time FullGC It will compress once
5. -XX:CMSInitiatingOccupancyFraction: Triggered when old age usage reaches this ratio FullGC( The default is 92, This is the percentage )
6. -XX:+UseCMSInitiatingOccupancyOnly: Use only the set recovery threshold (-XX:CMSInitiatingOccupancyFraction Set value ), If you don't specify ,JVM Only use the set value for the first time , Later, it will automatically adjust
7. -XX:+CMSScavengeBeforeRemark: stay CMS GC Start once before minor gc, The aim is to reduce the old age's references to the young , Reduce CMS GC The cost of marking the stage , commonly CMS Of GC Time consuming 80% It's all in the marking phase
8. -XX:+CMSParallellnitialMarkEnabled: Indicates multithreading at the time of initial marking , To shorten the stop the world
9. -XX:+CMSParallelRemarkEnabled: Multithreading during retargeting , To shorten the stop the world;

5、Garbage First The collector

G1(Garbage First) The collector is very different from the collector described earlier . Is a server oriented garbage collector , Mainly for machines equipped with multiple processors and large memory . Satisfy with a high probability GC At the same time as the pause time is required , High throughput performance .
Is based on Region The heap memory layout is the key to the implementation of this collector .G1 No longer adhere to fixed size and fixed number of generations of regional division , It's the continuous Java The heap is divided into several independent areas of equal size (Region), every last Region As needed , Play the new generation of Eden、Survivor Space or old age space .
Region There is a special kind of Humongous Area , Dedicated to storing large objects . As long as the object size exceeds Region Half of the capacity is considered as a large object . Every Region The size can be passed by parameter -XX:G1HeapRegionSize Set up , The value range is 1MB-32MB, And for 2 Of N The next power .
commonly Region Size is the heap size divided by 2048, For example, the heap size is 4096M, be Region The size is 2M.


G1 The collector can also be based on -XX:MaxGCPauseMillis Parameter to set garbage collection stop the world Time for .
The whole process is divided into 4 A step :
  1) Initial marker : Pause all other threads , Just mark it GC Roots Objects that can be directly associated with , fast
  2) Concurrent Tags : from GC Roots The process of traversing the whole object graph begins with the directly related object , This process takes a long time but does not need to pause the user thread , Can run concurrently with the garbage collection thread
  3) Final marker : To fix the concurrency flag period , The mark record of the part of the object whose mark changes due to the continuous operation of the program . Because the concurrency flag runs concurrently with the garbage collection thread , Therefore, some objects will be changed
  4) Screening and recovery : Is responsible for updating Region Statistical data , To each Region Sorted by recovery value and cost , Specify the recycle plan according to the pause time expected by the user . The operation here involves moving the living object , The user thread must be suspended , It is completed by multiple collector threads in parallel . The recycling algorithm mainly uses the replication algorithm , Will a region Copy the surviving object in to another region in , It's not like CMS That's it, because there are a lot of memory fragments that need to be cleaned up once ,G1 Using the replication algorithm to recycle almost no memory fragments .

G1 The collector maintains a priority list in the background , Each time according to the allowed collection time , Priority should be given to the most valuable Region( This is its name Garbage-First The origin of ), For example, a Region flowers 200ms Can recycle 10M The garbage , Another one Region flowers 50ms Can recycle 20M The garbage , With limited recovery time ,G1 Of course, the latter one will be preferred Region Recycling . This kind of use Region Partition the memory space and the way to recycle the priority area , To ensure the G1 The collector can be as efficient as possible in a limited time .

G1 Garbage collection and classification
YoungGC
YoungGC It's not about the existing Eden When the area is full, it will trigger immediately ,G1 The accountant calculated the present Eden How long does it take to recycle the area , If the recovery time is much less than the parameter -XX:MaxGCPauseMills Set value , So add the younger generation region, Continue to store new objects , Not immediately Young GC, Until the next time Eden The area is full ,G1 Calculate the recovery time close to the parameter -XX:MaxGCPauseMills Set value , Then it will trigger Young GC

MixedGC No FullGC, The old age's heap occupancy reaches the parameter (-XX:InitiatingHeapOccupancyPercent) The set value triggers , Recycle all of Young And part Old( According to expectation GC The pause time is fixed old Priority of district garbage collection ) And the big object area , Normal condition G1 Our garbage collection is to do MixedGC, Mainly using replication algorithm , Need to put each region Copy the surviving objects in the database to another region In go to , If not enough space is found during copying region Being able to host a copy object will trigger once Full GC

Full GC Stop system program , Then we use a single thread to mark 、 Clean and compress , Good free come out a batch of Region For the next time MixedGC Use , This process is very time consuming .

G1 Collector parameter settings
-XX:+UseG1GC: Use G1 The collector
-XX:ParallelGCThreads: Appoint GC Number of threads working
-XX:G1HeapRegionSize: Specify partition size (1MB~32MB, And it must be 2 Of N The next power ), By default, the whole heap is divided into 2048 Zones
-XX:MaxGCPauseMillis: Target pause time ( Default 200ms)
-XX:G1NewSizePercent: New generation memory initial space ( Default whole heap 5%)
-XX:G1MaxNewSizePercent: The largest memory space of the new generation
-XX:TargetSurvivorRatio:Survivor The filling capacity of the zone ( Default 50%),Survivor A group of objects in the area ( Age 1+ Age 2+ Age n Many age objects of ) The sum exceeds Survivor Regional 50%, At this time, the age will be n( contain ) All the above objects are put into the elderly generation
-XX:MaxTenuringThreshold: The maximum age threshold ( Default 15)
-XX:InitiatingHeapOccupancyPercent: In the old days, the occupied space reached the whole heap memory threshold ( Default 45%), Then the mixed collection of the new generation and the old generation was carried out (MixedGC), For example, we said that the heap default is 2048 individual region, If there is any approach 1000 individual region It's all old age region, It may trigger MixedGC 了
-XX:G1MixedGCLiveThresholdPercent( Default 85%) region Only when the number of live objects in is lower than this value will the region, If you exceed this value , There are too many survivors , Recycling doesn't mean much .
-XX:G1MixedGCCountTarget: In a recycling process, specify how many times to filter recycling ( Default 8 Time ), You can recycle for a while in the last filter recycle stage , Then pause recycling , Restore system operation , Start recycling later , In this way, the system can not be too long for a single pause .
-XX:G1HeapWastePercent( Default 5%): gc The process hollows out region Is the threshold sufficient , When mixing and recycling , Yes Region Recycling is based on replication algorithms , It's all about recycling Region Put the living objects in the other Region, And then this Region All rubbish objects in are cleared away , In this way, the recycling process will continue to empty out new Region, Once free Region The amount of heap memory 5%, At this point, the mixed recycling will be stopped immediately , It means that the mixed recycling is over .

What scene is suitable for use G1
1. 50% The above heap is occupied by live objects
2. The speed of object allocation and promotion varies greatly
3. Garbage collection takes a long time , exceed 1 second
4. 8GB The above heap memory ( recommended value )
5. The pause time is 500ms within

6、ZGC The collector

Enable the parameters :-XX:+UseZGC
Is in JDK11 New low latency garbage collector in .
Memory layout and G1 equally , use Region The heap memory layout of , It is divided into three types: large, medium and small :
  1) small Region: The capacity is fixed to 2MB, Used to store less than 256KB The little object of
  2) medium Region: The fixed capacity is 32MB, It is used to put to be greater than or equal to 256KB But less than 4MB The object of
  3) large Region: The capacity is not fixed , Can change dynamically , But it has to be 2MB Integer multiple , For placing in 4MB And above .
The operation process is divided into 4 A big stage :
  1) Concurrent Tags : And G1 identical
  2) And prepare for reallocation : According to the specific query conditions, we can find out what to clean up in this collection process Region, Will these Region Make up a reallocation set .
  3) Concurrent reallocation : yes ZGC The core stage of , To copy the living objects in the reallocation set to the new Region On , And redistribute each... In the set Region Maintain a forwarding table , Record the transition from the old object to the new object .
  4) Concurrent remapping : What remapping does is fix all references in the whole heap to old objects in the reallocation set .

7、 How to choose a garbage collector

1. Prioritize heap sizing for the server to choose
2. If memory is less than 100M, Using a serial collector
3. If it's a single core , And there is no pause time requirement , Serial or JVM Choose... For yourself
4. If pause time is allowed to exceed 1 second , Choose parallel or JVM Choose by yourself
5. If response time is the most important , And not more than 1 second , Using concurrent collectors
6. 4G You can use parallel,4-8G It can be used ParNew+CMS,8G The above can be used G1, A few hundred G For the above ZGC

8、GC Log view

1)GC essential information :jdk9 Before -XX:+PrintGC jdk9 after -Xlog:gc:
2)GC Details :jdk9 Before -XX:+PrintGCDetails jdk9 after -Xlog:gc*
3) see GC Front and rear stack 、 Method area available capacity change :jdk9 Before -XX:+PrintHeapAtGC jdk9 after -Xlog:gc+heap=debug:
4) see GC Concurrent time and pause time of user thread in the process :jdk9 Before -XX:+PrintGCApplicationConcurrentTime as well as -XX:+PrintGCApplicationStopTime jdk9 after -Xlog:safepoint:
5) Check the size of the generational area of the collector , Information about automatic adjustment :jdk9 Before -XX:+PrintAdaptiveSizePolicy jdk9 after -Xlog:gc+ergo*=trace:
6) View the age distribution information of the remaining objects after passing the collection :jdk9 Before -XX:+PrintTenuringDistribution jdk9 after -Xlog:gc+age=trace:

 

Four 、 Memory allocation and recycling strategy

1、 Priority is given to Eden Distribute

Most of the time , The object is the new generation Eden Regional distribution . When Eden When the area does not have enough space to allocate objects , The virtual machine will launch once Minor GC

2、 Large objects go directly into the old generation

A large object is one that requires a large amount of contiguous memory space Java object , The most typical large object is a very long string ( Picture turn base64 after ), Or an array with a large number of elements .
-XX:PretenureSizeThreshold Parameters ( Only right Serial and ParNew Collector valid ), Specifies that objects larger than this setting are assigned directly to the elderly , The purpose of this is to avoid Eden District and two Surivor Copy back and forth between zones , Generate a large number of memory copy operations .

3、 Long term survivors will enter the old age

Most collectors in virtual machines are generational ( The new generation , Old age ) Collect to manage heap memory , Then memory recycling must be able to decide which surviving objects should be placed in the new generation , Which surviving objects are placed in the elderly generation .
The object is usually in Eden Born in the district , If you go through the first time Monir GC Still alive after , And can be Survivor If it can be accommodated , The object will be moved to another Survivor In the area , And the starting object age is set to 1. The object is Survivor Every time I get through the area Monir GC, Age will increase 1, When he reaches a certain age ( Default 15), The object will be placed in the older generation . This upgrade is worth the threshold of the old age , Can pass -XX:MaxTenuringThreshold Parameter setting .

4、 Dynamic object age determination

If in Survivor The sum of the sizes of all objects below or equal to a certain age in the space is greater than Survivor Half of the space , Objects older than or equal to this age can directly enter the elderly generation .

5、 Space allocation guarantee

In the event of a Minor GC Before , The virtual machine must first check whether the largest available continuous space of the old generation is greater than the total space of all objects of the new generation , If this condition holds , So this time Minor GC Safe when available . Prevent all objects from entering the elderly generation .

 

 

版权声明
本文为[Xuanguo Guo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210558503380.html