preface

Only a bald head can be strong

The JVM read it while preparing for the interview and never had time to write notes. Now to a company internship, spare time to write, brush JVM blog, brush e-books.

The purpose of learning the JVM is simple:

  • Being able to know what the JVM is, what it does for us, and how it does it. Be able to understand something that you didn’t understand when you first learned
  • Have something to talk about in an interview
  • Can pack to force

(photo: zhuanlan.zhihu.com/p/25511795, assault delete)

Disclaimer: The full text by default refers to HotSpot VM

A brief talk about the JVM

1.1 Let’s start with a simple Java program

Now I have a JavaBean:


public class Java3y {

    / / name
    private String name;

    / / age
    private int age;

   	/ /... Various get/set methods /toString
}

Copy the code

A test class:


public class Java3yTest {

    public static void main(String[] args) {
        
        Java3y java3y = new Java3y();
        java3y.setName("Java3y"); System.out.println(java3y); }}Copy the code

We must have used javac to compile.java file code and Java commands to execute the compiled.class files.

Java source files:

When you use the IDE to click and run, you combine these two commands (compile and run) for easy development.

Generate a class file

Parse the class file to get the result

1.2 Compilation Process

The.java file is completed by the Java source compiler (javac.exe above), as shown in the flow chart below:

Java source compilation consists of the following three processes:

  • Parses and inputs into symbol tables
  • Annotation processing
  • Semantic analysis and generation of class files

1.2.1 Compile time – Syntax sugar

Syntactic sugar can be thought of as “tricks” implemented by compilers that can lead to “big efficiency gains”.

The most notable example is generics, which is a syntactic sugar that we often use!

  • Generics only exist in Java source code and are replaced by Raw types (also known as bare types) after compilation. This process is also known as generic erasure.

With generics in hand:

  • Cleaner code [no cast]
  • More robust applications (as long as there are no warnings at compile time, there are no ClasscastExceptions at run time)
  • Readability and stability [when writing collections, the type is qualified]

Learn more about generics:

  • Segmentfault.com/a/119000001…

1.3JVM implementation cross-platform

At this point, we compile our.java source files using the javac.exe compiler to generate.class files!

These.class files obviously cannot be run directly, unlike C (which compiles CPP and generates an EXE file to run directly).

These.class files are parsed by the JVM!

  • The JVM runs on top of the operating system, and each operating system has different instructions. The JDK is OS specific, and as long as your local system has JDK installed, it will be compatible with the current system.
  • The class bytecode runs on the JVM, so it doesn’t matter which operating system the class bytecode is compiled on, as long as it complies with the JVM specification, then the bytecode file is runnable.
  • So Java is cross-platform — compile once, run everywhere!

1.4 Class files and the JVM

1.4.1 Class loading timing

Will both. Class files generated in our example now be loaded directly into the JVM?

The VIRTUAL machine specification specifies that there are only five cases in which classes must be “initialized” immediately (class files loaded into the JVM) :

  • Create an instance of the class (new). Access a static variable of a class or interface, or assign a value to that static variable, and call the class’s static method
  • Mode of reflection
  • If you initialize a subclass of a class, its parent class is initialized as well
  • A class that is marked as a startup class when the Java virtual machine starts, using the java.exe command directly to run a main class (the class that contains the main method).
  • When using JDK1.7’s dynamic language support (….)

So said.

  • Java classes are loaded dynamically. Instead of loading all classes at once and then running them, the underlying classes (like the base classes) that the program runs on are fully loaded into the JVM, and other classes are loaded as needed. This, of course, is to save memory overhead.

1.4.2 How do I load classes into the JVM

Class files are loaded into the JVM through the class loader!

Java has three types of loaders by default:

Responsibilities of each loader:

  • $JAVA_HOME (jre/lib/rt.jar); Bootstrap ClassLoader ($JAVA_HOME, jre/lib/rt.jar)
  • $JAVA_HOME jre/lib/*. Jar or -djava.ext. dirs jar package
  • 3) App ClassLoader: it is responsible for recording the classes in the jar package and directory specified in classpath

Working process:

  • 1. When an AppClassLoader loads a class, it does not attempt to load the class itself. Instead, it delegates the request to the parent class loader, ExtClassLoader.
  • 2. When ExtClassLoader loads a class, it does not attempt to load the class itself in the first place. Instead, it delegates the class loading request to BootStrapClassLoader.
  • 3. If the BootStrapClassLoader fails to load (for example, the class cannot be found in $JAVA_HOME/jre/lib), the ExtClassLoader will be used to try loading.
  • 4. If the ExtClassLoader fails to load, AppClassLoader is used to load the ExtClassLoader
  • 5. If the AppClassLoader also fails to load, an exception ClassNotFoundException will be reported

This is called the parental delegation model. Simply put: If a classloader receives a class-loading request, it does not attempt to load the class itself, but delegates the request to the parent loader, up the chain.

Benefits:

  • Prevent multiple copies of the same bytecode in memory (security perspective)

Special note:

  • The class loader, after successfully loading a class, will get thejava.lang.ClassClass instances are cached. The next time the class is loaded, the class loader uses the cached instance of the class directly, andReloading will not be attempted.

1.4.2 Detailed process of class loading

After the loader is loaded into the JVM, there are several steps:

  • Load, find and load the binary data of the Class, and also create an object of java.lang.Class in the Java heap.
  • Connection, connection contains three parts: verification, preparation, initialization.
    • 1) Verification, file format, metadata, bytecode, symbol reference verification;
    • 2) Prepare, allocate memory for class static variables and initialize them to default values;
    • 3) Parse and convert symbolic references in the class to direct references
  • Class to assign the correct initial value to a static variable of the class.

1.4.3JIT instant editor

We might think that the JVM, after loading these class files, would fetch and perform the parser parsing on each bytecode piece by piece.

But if so, that’s too slow!

Our JVM is implemented like this:

  • These Java bytecodes are recompiled and optimized to generate machine code that the CPU executes directly. The resulting code will be more efficient.
  • Compilation also takes time. We usually compile hot code and parse non-hot code directly.

Hot code explanation: a method called many times. A loop body that executes multiple times

Hotspot detection is used to detect whether it is a hotspot code. There are two methods of hotspot detection:

  • The sampling
  • counter

Currently HotSpot uses counters and has two types of counters for each method:

  • Invocation Counter
  • Back EdgeCounter counter.
  • Both counters have a certain threshold, provided that the virtual machine’s operating parameters are determined. When the counter overflows, JIT compilation is triggered.

1.4.4 Back to the example

As our program goes, our Java3ytest. class file will be loaded into the JVM by the AppClassLoader (because neither the ExtClassLoader nor the BootStrap loader will load it (parent-delegate model).

Then we discovered that to use Java3y, our java3y. class file would be loaded into the JVM by the AppClassLoader (because neither the ExtClassLoader nor the BootStrap loader would load it [parent-delegate model])

For details:

  • www.mrsssswan.club/2018/06/30/… — Shallow solution to JVM loading class file
  • JIT zhuanlan.zhihu.com/p/28476709—JVM gossip

Read more:

  • www.ibm.com/developerwo… — Delve into Java class loaders
  • www.ibm.com/developerwo… — Simple JIT compiler
  • www.zhihu.com/question/46… — What are the actual usage scenarios of Java ClassLoader?

1.5 What does the JVM do after the class is loaded?

After the class load check passes, the virtual machine next allocates memory for the new objects.

1.5.1 Memory model for the JVM

First let’s take a look at how the JVM’s memory model looks:

  • The memory model of the JVM based on JDK1.8 is drawn in detail.

Take a quick look at the memory model to see what exactly each region stores (and does) :

  • Heap: Holds object instances, where almost all object instances are allocated memory
  • Virtual machine Stack: Virtual machine Stack describes the memory model of Java method execution. When each method is executed, a Stack Frame is created to store information about local variables, operation Stack, dynamic links, method exits, etc
  • Local method stack: The local method stack serves the Native methods used by the VIRTUAL machine.
  • Method area: stores class metadata information that has been loaded by the virtual machine (meta space)
  • Program counter: Line number indicator of bytecode executed by the current thread

1.5.2 Process in the example

Let me outline the workflow in our example:

  • 1, through thejava.exerunJava3yTest.classWhich is then loaded into the JVM,The meta space stores information about the class(including class name, method information, field information..) .
  • 2. The JVM then finds the Java3yTest’s main entry (main), creates a stack frame for main, and starts executing main
  • The first command of the main function isJava3y java3y = new Java3y();The JVM is told to create a Java3y object, but there is no Java3y class information in the method area, so the JVM immediately loads the Java3y class and puts the Java3y class type information in the method area.
  • 4. The first thing the Java virtual machine does after loading the Java3y class is allocate memory for a new Java3y instance in the heap, and then call the constructor to initialize the Java3y instance, which holds the type information pointing to the Java3y class in the method area (including the method table). The underlying implementation of Java dynamic binding
  • 5. When usedjava3y.setName("Java3y");When the JVMLocate a Java3Y object based on a Java3Y reference, and locate the type information of the Java3y class in the method area according to the reference held by the Java3y objectMethod tableTo obtainsetName()The bytecode address of the function
  • 6, forsetName()The function creates a stack frame and starts runningsetName()function

At the micro level, a lot of work is done, as mentioned above in the class loading process (load -> connect (validate, prepare, parse)- > initialize), and the JVM allocates memory for the class after it is loaded (a lot of work goes into allocating memory). Since these steps are not step-by-step, there are a lot of “chaotic bootstrap” processes that are difficult to describe.

  • Extending reading (first Class Object or the Object) : www.zhihu.com/question/30…

References:

  • www.cnblogs.com/qiumingchen… — The process by which Java programs are compiled and run
  • Zhuanlan.zhihu.com/p/25713880—Java JVM running mechanism and basic principle

1.6 A brief talk about the various constant pools

At the time of writing this article, I thought I was interested in String s = “aaa”; These were no problem until I ran into methods like string.intern () and things like String s1 = new String(“1”) + new String(“2”); When you mix it together

  • I realized I was still too young.

First of all, I read this article by Meituan technical team: tech.meituan.com/in_depth_un… — parse String#intern

Yeah, and then it was all over the place. Let me paraphrase his example:


public static void main(String[] args) {
    String s = new String("1");
    s.intern();
    String s2 = "1";
    System.out.println(s == s2);

    String s3 = new String("1") + new String("1");
    s3.intern();
    String s4 = "11";
    System.out.println(s3 == s4);
}

Copy the code

The printed result is

  • Jdk7, 8 under false true

After switching places:


public static void main(String[] args) {

    String s = new String("1");
    String s2 = "1";
    s.intern();
    System.out.println(s == s2);

    String s3 = new String("1") + new String("1");
    String s4 = "11";
    s3.intern();
    System.out.println(s3 == s4);
}
Copy the code

The printed result is:

  • Jdk7, 8 under false false

The article has a very detailed explanation, but I was still confused after reading it a few times. Therefore, I know that there are still loopholes in my knowledge, and I read the article written by R University before:

  • Rednaxelafx.iteye.com/blog/774673… String s = new String(“xyz”); How many String instances have been created

After I read it, I was even more confused.

Later, I saw this answer on Zhihu:

  • www.zhihu.com/question/55… When does the “literal” in Java new String(” literal “) enter the String constant pool?

Combined with online information and my own thinking, the following sort out my understanding of constant pool ~~

1.6.1 Condition of each constant pool

For after JDk1.7:

  • The constant pool is in the heap
  • The run-time constant pool is in the heap
  • The string constant pool is in the heap

The constant pool stores:

  • Literals: text strings and so on —-> String literals enclosed in double quotes go in here
  • Symbolic References
    • Fully Qualified Name of class and interface
    • Field name and Descriptor
    • The name and descriptor of the method

The Constant Pool Table is used to store various literal and symbolic references generated at compile time in the runtime Constant Pool in the method area after the class is loaded.

The runtime constant pool is now in a different location (originally in the method area, now in the heap), but it is clear that the data in the constant pool is stored in the runtime constant pool when the class is loaded!

In HotSpot VM, a global table that records Interned Strings is called StringTable, which is essentially a HashSet. Note that it stores only references to instances of java.lang.String, not the contents of String objects

String constant pools only store references, not content!

Look again at our Intern method:


 * When the intern method is invoked, if the pool already contains a
 * string equal to this {@code String} object as determined by
 * the {@link #equals(Object)} method, then the string from the pool is
 * returned. Otherwise, this {@code String} object is added to the
 * pool and a reference to this {@code String} object is returned.
 
Copy the code
  • If the current string exists in the constant pool, a reference to it from the constant pool is returned.
  • If the string is not in the constant pool, the string reference is saved to the constant pool and then returned directly!

1.6.2 Analyzing the topic

I was going to explain it as a comment, but it’s hard to explain. Let me draw a picture…


public static void main(String[] args) {

 
    String s = new String("1");

    s.intern();


    String s2 = "1";

    System.out.println(s == s2);// false
    System.out.println("----------- follow public account: Java3y-------------");
}
Copy the code

String s = new String(“1”);

Second sentence: s.ntern (); If a string object “1” already exists in the string constant pool, return (but not receive) a reference to the heap in the string constant pool –> the s reference still refers to the object in the heap

String s2 = “1”; Returns a string constant pool reference to a string in the heap

It’s easy to see that the two references are different! So return false.



    public static void main(String[] args) {

        System.out.println("----------- follow public account: Java3y-------------");

        String s3 = new String("1") + new String("1");


        s3.intern();


        String s4 = "11";
        System.out.println(s3 == s4); // true
    }
Copy the code

S3 = new String(“1”) + new String(“1”); s3 = new String(“1”) + new String(“1″); Note: at this point the **”11” object does not hold a reference to ** in the string constant pool.

S3. Intern (); Finding that the “11” object is not in the string constant pool, saves a reference to the current string in the string constant pool and returns (but does not receive) a reference to the current string

String s4 = “11”; String constant pool reference found, return string constant pool reference

According to the above: returns true~~~

If you’re still confused, try receiving the values that intern() returns and looking at the diagram above.


The following is for you to do, to see if you have mastered:


    public static void main(String[] args) {

        String s = new String("1");
        String s2 = "1";
        s.intern();
        System.out.println(s == s2);//false

        String s3 = new String("1") + new String("1");
        String s4 = "11";
        s3.intern();
        System.out.println(s3 == s4);//false
    }
Copy the code

There are:


    public static void main(String[] args) {
        String s1 = new String("he") + new String("llo");
        String s2 = new String("h") + new String("ello");
        String s3 = s1.intern();
        String s4 = s2.intern();
        System.out.println(s1 == s3);// true
        System.out.println(s1 == s4);// true
    }
Copy the code

1.7GC garbage collection

GC garbage collection is a very important topic in the JVM and should be covered in great detail. But along the way, I’ve found good articles on recycling.

So, here I just briefly introduce the things of garbage recycling, detailed can refer to the following interview questions and finally give relevant materials to read ~

1.7.1 Introduction to JVM garbage Collection

In C++, we know that created objects need to be manually deleted. Our Java programs run in the JVM, which helps us “automatically” recycle unwanted objects, which is very convenient for us.

Although “automatic” retrievals objects we don’t need, if we want to be strong, we have to go bald.. No, we need to know how it works and what the theoretical knowledge is.

First, the JVM collects garbage, which is garbage that is no longer needed in our program. The first thing the garbage collector does before collecting the heap is determine which of these objects are “alive” and which are “dead.” There are two common ways to determine which objects are “dead” :

  • Reference counting -> This is difficult to solve the problem of circular references between objects
  • Reachability analysis algorithms -> Mainstream JVMS use this approach

It is now possible to determine which objects are “dead”, and we now want to recycle these “dead” objects. There are several algorithms for recycling:

  • Mark-clear algorithm
  • Replication algorithm
  • Mark-collation algorithm
  • Generational collection algorithm

See the interview questions below for details of these algorithms

The JVM uses exact GC for both the reachability analysis algorithm and the garbage collection algorithm. The JVM uses a set of data structures called OopMap to store all of the object references (so you don’t have to traverse the entire memory to find them, space for time). And not all instructions will generate OopMap, only OopMap will be generated at the safe point, and GC will start at the safe zone.

  • With the help of OopMap, HotSpot can quickly and accurately perform GC Roots enumeration (accessibility analysis).

The garbage collection algorithm described above is only a methodology, implementation is garbage collector:

  • Serial collector
  • ParNew collector
  • Parallel avenge
  • Serial Old collector
  • Parallel Old collector
  • CMS collector
  • G1 collector

Most of these collectors can be combined with one another

1.8JVM parameters and tuning

Many of you who have worked on JavaWeb projects (SSH/SSM) have probably encountered an error like OutOfMemory. General solution is also very convenient, in the start of the time to add a parameter on the line.

There are a lot of things about the JVM – its memory partitioning, its various garbage collectors.

The size of the allocation of memory ah, which collector ah, these can be specified by us according to the needs, the reality, here is not detailed, such as the real use of the time to come back to fill the pit ~~~~

References:

  • www.cnblogs.com/redcreen/ar… –JVM series 3 :JVM parameter Settings, analysis

Second, JVM interview questions

Here are some common JVM interview questions to help you understand and fill in the gaps:

  • 1. Detailed JVM memory model
  • 2, tell me when memory overflow, memory leak?
  • 3. Talk about Java thread stacks
  • 4. What are the criteria for determining the progression from the younger generation to the older generation of the JVM?
  • 5. FullGC occurs frequently in JVM. How to check problems online?
  • 6. Why is the parent delegate pattern used for class loading? Are there any scenarios that break this pattern?
  • 7. Class instantiation order
  • 8. JVM garbage collection mechanism, when to trigger MinorGC, etc
  • What does a complete GC flow (from YGC to FGC) look like in the JVM
  • 10, various recyclers, their advantages and disadvantages, focusing on CMS, G1
  • 11. Various recycling algorithms
  • 12, OOM error, StackOverflow error, Permgen space error

Subject:

  • www.jianshu.com/p/a07d1d400…

2.1 Detailed JVM memory model

According to the JVM specification, THE JVM memory is divided into five parts: virtual machine stack, heap, method area, program counter, and local method stack.

– will probably talk about PermGen before jdk1.7 and replace it with Metaspace

  • Data stored in permanent generation: symbol references are transferred to native heap; Literals (interned strings) are transferred to the Java Heap; Class statics are moved to the Java Heap
  • Metaspace stores metadata of a class
  • Similar in nature to permanent generations, meta-spaces are implementations of method areas in the JVM specification. However, the biggest difference between a meta-space and a permanent generation is that the meta-space is not in the virtual machine, but uses local memory.
  • The advantages of substitution are as follows: First, the string exists in the permanent generation, which is prone to performance problems and memory overflow. Permanent generation introduces unnecessary complexity to the GC and is inefficient for collection

Image: blog.csdn.net/tophawk/art…

References:

  • www.cnblogs.com/paddix/p/53…

2.2 When do memory leaks occur?

The causes of memory leaks are simple:

  • Object is reachable (always referenced)
  • But the object will not be used

Common examples of memory leaks:


 public static void main(String[] args) {

        Set set = new HashSet();

        for (int i = 0; i < 10; i++) {
            Object object = new Object();
            set.add(object);

            // Set it to null. I no longer use this object
            object = null;
        }

        // But the set also maintains a reference to obj, and the GC does not reclaim object objects
        System.out.println(set);
    }
Copy the code

Fixing the memory leak problem is simple, set the set to NULL, and you can avoid the memory leak problem. Other memory leaks have to be analyzed step by step.

Memory Leak References:

  • www.ibm.com/developerwo…

Causes of memory overflow:

  • Memory leaks cause stack memory to grow, triggering a memory overflow.
  • A large number of JAR, class files loaded, not enough space to load classes, overflow
  • Operating on a large number of objects causes the heap memory space to become full and overflow
  • Nio directly operates on the memory and overflows the memory

Solution:

  • Check to see if the program has memory leaks
  • Set parameters to increase space
  • Does the code have an infinite loop or loop that produces too many duplicate object entities,
  • Check to see if NIO direct operation memory is used.

References:

  • www.cnblogs.com/bingosblog/…
  • www.importnew.com/14604.html

2.3 Talk about thread stacks

The thread stack refers to the virtual machine stack.

The JVM specification gives each Java thread its own separate JVM stack, which is the call stack for Java methods.

When the method is called, a stack frame is generated. The stack frame is stored in the virtual machine stack. The stack frame stores the local variable table, operand stack, dynamic link, method return address and other information

When a thread is running, only one stack frame is active, which is called “current active stack frame”. The current active stack frame is always the top element of the virtual machine stack.

Check the thread status using the JStack tool

References:

  • Wangwengcn.iteye.com/blog/162219…
  • www.cnblogs.com/Codenewbie/…
  • Blog.csdn.net/u011734144/…

2.4 What are the criteria for judging the promotion process from the younger generation to the older generation of JVM?

  1. Some objects are copied back and forth between the From and To sections, exchanged 15 times (as determined by the JVM parameter MaxTenuringThreshold, which defaults To 15), and eventually saved To the old age if they are still alive.
  2. If the size of the object is more than half that of Eden, it will be allocated to Old directly; if old cannot be allocated, a majorGC will be made; if the object is less than half that of Eden but there is not enough space, minorgc will be performed, that is, new-generation GC.
  3. After minor GC, survivor is placed in the old age
  4. Dynamic age judgment: objects older than or equal to a certain age exceed half of survivor space, and objects older than or equal to a certain age directly enter the old age

2.5JVM fullGC occurs frequently, how to check problems online

Full GC: full GC:

  • If there is perm Gen (jdK1.8 is not available),When you need to allocate space to perm Gen, but there is not enough space, triggers the full GC.
    • So let’s see if the value of the Perm Gen field is set too small.
  • System.gc()Method call
    • This general no one to call it ~~~
  • whenstatisticalThe resulting Minor GC is scaled up to the average size of the old generationLarger than the remaining space of the old age, triggers the full GC (this can be viewed from multiple angles)
    • Are large objects frequently created (maybe Eden is too small)(large objects are allocated directly in the old age, so there is not enough space in the old age –> so gc is frequent)
    • Is the space set too small for the old age?

2.6 Why is the parent delegate pattern used for class loading, and are there any scenarios that break this pattern?

An important use of the parent delegate model is to address security issues during class loading.

  • Let’s say a developer writes his own code calledjava.lang.ObjectClass to trick the JVM. Now he wants to use customizationClassLoaderTo load your ownjava.lang.ObjectClass.
  • Fortunately, however, the parental delegation model won’t let him succeed. Because the JVM takes precedenceBootstrap ClassLoaderIs found under the path ofjava.lang.ObjectClass and load it

Does Java class loading necessarily follow the parental delegation model?

  • In real development, we can break this mechanism by customizing the ClassLoader and overwriting the loadClass method of the parent class.
  • SPI breaks the parental delegation mechanism (SPI: service provision discovery). SPI data:
    • zhuanlan.zhihu.com/p/28909673
    • www.cnblogs.com/huzi007/p/6…
    • Blog.csdn.net/sigangjun/a…

References:

  • Blog.csdn.net/markzy/arti…

2.7 Class instantiation order

  • 1. Superclass static members and static initializer blocks are executed in the order they appear in the code
  • 2. Subclass static members and static initializer blocks in the order they appear in code
  • 3. The parent instance members and instance initializer blocks are executed in the order they appear in the code
  • 4. Parent class constructor
  • 5. Subclass instance members and instance initializer blocks are executed in the order they appear in the code
  • 6. Subclass constructor

Check to see if you really understand:


class Dervied extends Base {


    private String name = "Java3y";

    public Dervied(a) {
        tellName();
        printName();
    }

    public void tellName(a) {
        System.out.println("Dervied tell name: " + name);
    }

    public void printName(a) {
        System.out.println("Dervied print name: " + name);
    }

    public static void main(String[] args) {

        newDervied(); }}class Base {

    private String name = "Public Account";

    public Base(a) {
        tellName();
        printName();
    }

    public void tellName(a) {
        System.out.println("Base tell name: " + name);
    }

    public void printName(a) {
        System.out.println("Base print name: "+ name); }}Copy the code

Output data:


Dervied tell name: null
Dervied print name: null
Dervied tell name: Java3y
Dervied print name: Java3y

Copy the code

“Like” and “hahaha” for someone who gets it wrong the first time

2.8JVM garbage collection mechanism, when to trigger operations such as MinorGC

MinorGC is triggered when The Eden sector in Young Gen is full.

2.9 What does a complete GC flow (from YGC to FGC) look like in the JVM

This question is not very clear meaning (level limited… Leave a comment in the comments if you know what this means.

  • Because as I understand it, FGC is not yGC

What are YGC and FGC

  • YGC: Gc is performed on the new generation reactor. The frequency is high because most objects have short life spans and are recycled in the Cenozoic. Performance costs are low.
  • FGC: Heap-wide GC. FGC is triggered when the default heap usage reaches 80%(adjustable). In our production environment, for example, FGC is triggered very infrequently, sometimes once every 10 days or a week.

When do YOU perform YGC and FGC

  • A. Eden space is insufficient, execute young GC
  • B. Ld space is insufficient, perm space is insufficient, call methodSystem.gc(), pessimistic strategy in YGC, and full GC is performed in JMAP — dump:live

2.10 Various recycling algorithms

There are three basic GC algorithms:

  • Mark-clear algorithm
  • Replication algorithm
  • Mark-compression algorithm
  • The typical garbage collector uses a generational collection algorithm (which is essentially a combination of the above algorithms, using different algorithms for different regions).

Specific:

  • Mark-sweep is, as its name suggests, a “mark-sweep” algorithm that is divided into two phases: first, it flags all objects that need to be reclaimed, and then it dumps all of them.
  • Copying algorithms, a collection algorithm for “Copying,” partitioning available memory into two equally sized pieces by capacity, using only one piece at a time. When this area of memory is used up, the surviving objects are copied to the other area, and the used memory space is cleaned up again.
  • Mark-compress algorithm, the marking process is still the same as the mark-clean algorithm, but instead of cleaning up the recyclable objects directly, the next step is to move all surviving objects to one end and then clean up the memory directly beyond the end boundary
  • Generational Collection algorithms, “Generational Collection” algorithms, divide the Java heap into Generational and older generations so that the most appropriate Collection algorithm can be used for each generation.

2.11 Advantages and disadvantages of various recyclers, especially CMS and G1

The figure, from Understanding the Java Virtual Machine: Advanced JVM Effects and Best Implementations, shows a line between the two collectors, indicating that they can be used together.

  • Serial collector, the Serial collector is the oldest, most stable, and efficient collector, but may produce a long pause and use only one thread to collect.
  • The ParNew collector, which is actually a multithreaded version of the Serial collector.
  • The Parallel collector, similar to the ParNew collector, focuses on the throughput of the system.
  • The Parallel Old collector, the Parallel Old is an older version of the Parallel Avenge collector that uses a multithreaded “mark-collation” algorithm
  • The CMS collector, a Concurrent Mark Sweep (CMS) collector, is a collector whose goal is to obtain the shortest collection pause time. It consumes extra CPU and memory resources, which increases the burden on the system when CPU and memory resources are tight and CPU resources are small. CMS cannot handle floating garbage. CMS’s “mark-sweep” algorithm will lead to a large amount of space debris.
  • G1 collector, gbage-first (G1) is a server-oriented Garbage collector for machines equipped with multiple processors and large memory. High throughput performance characteristics while meeting the GC pause time requirements with extremely high probability.

2.12 StackOverflow error, Permgen space error

Stackoverflow error:

  • In the virtual machine stack (thread request stack depth is greater than the maximum depth allowed by the virtual machine stack lock)

Permgen Space error (for pre-jdk 1.7) :

  • Load a lot of class files
  • The constant pool memory overflowed

Third, summary

In general, the JVM is more theoretical at the initial level, and you may need to do concrete things to get a better understanding. This article is mainly into a door ~

This article is an overview of some of the most important things about the JVM, and I’m going to learn to write about SpringCloud.

References:

  • In-depth Understanding of Advanced Features and Best Practices of the Java Virtual Machine JVM (2nd edition)
  • Column: pure smile JVM zhuanlan.zhihu.com/p/25511795
  • Column: SexyCode JVM blog.csdn.net/column/deta…
  • JavaGC process: blog.csdn.net/yangyang123…

If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y.

Article table of Contents navigation:

  • Zhongfucheng.bitcron.com/post/shou-j…