当前位置:网站首页>JVM second conversation -- JVM memory model and garbage collection

JVM second conversation -- JVM memory model and garbage collection

2022-07-01 14:44:00 Procedural ape with hair!

1.JVM Memory model

1.1 Java Object layout

 Insert picture description here

Alignment filling : To ensure that the size of the object is 8 Integer multiples of bytes , Automatic alignment , Avoid multiple loads

1.2 Heap Heap memory distribution

  • First use jdk/bin/jvisualvm.exe Tools for , Can also be cmd Input directly in the window jvisualvm. Open it later in Tools - Plug in installation Visual GC, Monitor the currently started java service
     Insert picture description here

It can be divided into Metaspace Metadata ( Non heap )、Old District old age 、Eden(Survivor0、Survivor1) The Cenozoic is also referred to as Young District

1.2.1 Old District old age

  • Every time GC Recycling , Target age +1, Greater than 15 Those that have not been recycled for the first time are added to the elderly generation
  • The object memory size is larger than that of the new generation , Then directly join the elderly generation

1.2.2 Young Cenozoic in the area

Because the life cycle of most objects in the new generation is relatively short , Recycling will lead to Young The area space is discontinuous , The problem of space debris .
 Insert picture description here
Cannot allocate when allocating objects that require multiple memory cells , Will cause GC Recycling leads to and CPU Grab time .

So will Young The area is divided into Eden Area and Survivor District

  • Eden Only new objects are stored in the area
  • As long as it is recycled, put it in S District ,Eden The area can be relatively continuous , But after recycling again S There will also be space debris problems in the area , It will still cause the object to be stuck
  • So we distinguish S0(Survivor From)、S1(Survivor To), Each recovery is transferred to the next area , Always promise S0 perhaps S1 One is empty , This solves the problem of fragmentation
  • Eden Area and S0、S1 Is the percentage of 8:1:1
  • In case the newly generated object is relatively large ,S0、S1 Not enough memory , Need to borrow memory from the elderly , This is called a guarantee mechanism

 Insert picture description here
Will always guarantee S0 perhaps S1 One is empty

2.JVM Garbage collection

2.1 Young GC

Contains Eden、S District , The smallest GC It's called Minor GC

2.2 Old GC

Major GC, Usually accompanied by Minor GC, amount to Full GC

2.3 Full GC

Young GC+ Old GC (+MateSpace GC)

It can lead to stop the work , Try to reduce as much as possible Full GC The frequency of
Allow a certain range of Young GC

2.4 simulation Heap District OOM

  • First prepare the code
List<User> str = new ArrayList<>();

@GetMapping("/while")
public void while1() {
    
    while (true){
    
        str.add(new User());
    }
}
  • Set up JVM Heap memory size
-Xms40M -Xmx40M
  • Heap memory distribution and log screenshot
     Insert picture description here
    The above figure shows the garbage collection process :
  • A newly generated object enters Eden District , Find out Eden Zone out of memory , The trigger Young GC
  • Young GC First of all, S1 To recycle , Generation age that has not been recycled +1, Transferred to the S0 perhaps Old District ( Meet the age of generations )
  • And then to Eden Area for recycling , Those not recycled are transferred to S0, So as to reserve space for new objects
  • After recycling ,Eden District or S0 perhaps Old Insufficient space in the area will lead to OOM

2.5 simulation Metaspace District OOM

Java8 Use Metaspace To replace the permanent generation .Metaspace It's the method area Hotspot In the implementation of , Not in virtual machine memory, but directly using local memory .

stay Java8 in ,Class、Metadata Stored in Metaspace In metadata , Forever (Java8 After being Metaspace replace ) Stored some information :
1. Class information loaded by virtual machine
2. Constant pool
3. Static variables
4. Real time compiled code

To simulate Metaspace Space overflow , You can constantly generate proxy classes and add , It will trigger for so long Metaspace OOM

  • java Code
public class MetaspaceTest {
    

    static class User {
    
        String name;
    }

    public static void main(String[] args) {
    
        int i = 0;
        try {
    
            while (true) {
    
                i++;
                Enhancer enhancer = new Enhancer();
                enhancer.setSuperclass(User.class);
                enhancer.setUseCache(false);
                enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> methodProxy.invokeSuper(o, args));
                enhancer.create();
            }
        } catch (Throwable e) {
    
            System.out.println("i=" + i);
            e.printStackTrace();
        }
    }
}
  • jvisualvm Tool monitoring and logging
     Insert picture description here
    as for Metaspace Why is it not filled , Because in Java8 in Metaspace Not in virtual machine memory, but directly using local memory .

3.JVM Garbage collector

3.1 How to determine the garbage object

  1. Reference count , There may be a circular reference problem, so that neither object can be recycled
  2. Accessibility analysis , Confirm one GC Root, Start from it , Check whether an object is reachable , Unreachable objects are garbage objects

3.2 GC Root

  • Local variable table in virtual machine stack ( Stack -> From the variables being executed in the method area )
  • Method area constants or static Variable , Variables in the local method stack
  • Class loader
  • Thread

3.3 Recovery algorithm

1. Tag clearing algorithm ( The living object 、 Mark the object 、 Unused space )

  • Determined as garbage object during scanning , Mark , The next scan will be recycled
  • Both marking and clearing scan the entire heap memory space , More time-consuming , After removal, space debris is discontinuous

2. Tag copy algorithm

  • Divide an area , Copy the living objects to the new area after marking , Then empty the whole marked area directly , Equate to s0/1
  • Although the space is continuous , But it is also a waste of space

2. Marking algorithm

  • Move the living objects during the process of clearing after marking

3.4 Garbage collector

Application of the above algorithm , Apply different recycling algorithms to different generations
The new generation : Tag copy algorithm , Old age : Mark clear 、 Sorting algorithm

3.4.1 Serial GC

-XX:+UseSerialGC

  • Single thread garbage collector , More applicable to single core CPU, Less memory space
  • Applicable to new and old age
  • shortcoming : Will pause the business code thread , Because the memory address in the heap will change , You cannot let threads use objects that no longer exist

3.4.2 Parallerl GC

-XX:+UseParallerlGC

  • Multithreading , But it will make the application pause , Applicable to new and old age

3.4.3 Concurrent Mark Sweep(CMS)

-XX:+UseConcMarkSweepGC

  • It's using a tag removal algorithm , There is a problem of space debris , Only for the old days
  • Garbage collector of emergency class , The user thread and garbage collection thread are running simultaneously , Low pause time

3.4.4 G1 Garbage Collector

-XX:+UseG1GC

  • Try to meet the pause time goal set by the user , It solves the problem of space debris very well , High throughput
  • Tag collation algorithm used , Applicable to new and old age

3.4.5 Z GC

-XX:+UseZGC

  • Very small pause time , But some throughput will be sacrificed

4. JVM Tuning latitude

Determine the most reasonable garbage collection period based on business , There are mainly the following latitudes

  • Serial : There is only one garbage collector ,Serial
  • parallel : Multiple garbage collectors , The business code thread will pause Parallerl GC, Pay more attention to throughput
  • Concurrent : Multiple garbage collectors , Business code runs together ,CMS、G1、ZGC, Pay more attention to the pause time

4.1 Pause time

Response time of service interface , Garbage collector performs garbage collection and Client Time to execute response

4.2 throughput

The number of requests or updates completed in the time period , Run user code time / Total time to run user code and garbage collection

That's all for this chapter .

Last one :JVM First words – JVM Introduction details and runtime data area analysis
Next :JVM Third words – JVM Performance tuning practice and record of high-frequency interview questions

There is a good way to study , There's no end to learning how to make a boat

原网站

版权声明
本文为[Procedural ape with hair!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011443190730.html