The JVM inquiry

Understand the JVM?

Jvm Java virtual machine, is a virtual computer, is through the actual computer simulation of a variety of computer functions to achieve, a very important feature of the Java language is platform independent, and the use of Java virtual machine is the key to achieve this feature

Java8 virtual machine and previous changes updated?

Revoking the permanent tape and referencing the meta space: In the hotSpot virtual machine, in JDK 1.6, the actual team designed the method area to be permanent, so that the GC working area can be extended to the method area. This strategy avoids the need to design a separate garbage collection mechanism for the method area. The disadvantage is that the collection conditions for the method area are very strict. In jdk1.7, the design team was aware of this problem, but only removed the string constant pool from the method area permanently. In jdk1.8, the concept of permanent tape is no longer present, and the rule in the permanent space is replaced by a meta-space: Each class loader has a special storage space. It does not reclaim a class separately. The location is fixed, but when the class loader is no longer alive, the space associated with it is removed.

What is OOM?

It’s called “OUT OF Memory,” which means you’ve run OUT OF Memory, From Java. Lang. OutOfMemoryError official word Thrown when the Java Virtual Machine always the allocate an object because it is out of Memory, and no more memory could be made available by the garbage collector This error is thrown when the JVM does not have enough memory to allocate space for an object and the garbage collector has run out of space to reclaim.

Why OOM?

1, the allocation of less memory: for example, the VM itself can use too little memory (usually specified by the VM parameters at startup) 2, the application used too much, and did not release, waste, this will cause memory leakage or memory overflow

A memory leak

The used memory is confiscated and released. As a result, the VM cannot use the memory again. In this case, the memory is leaked

Out of memory

In the past, using C or C++, we had to take care of the application and release of memory. If we applied for memory, we ran out of memory and did not release it. For example, in C++, new was applied but there was no delete, we might have a memory leak. Too many and you run out of memory.

And in the Java language, because of the garbage collection mechanism automatically, so we usually don’t have to take the initiative to release unused objects of memory, namely, in theory, is not the existence of “memory leak”, but if the improper coding, such as an object of reference on the global MAP, although method over, However, because the garbage collector will recycle the memory of the object according to the reference of the object, the object can not be reclaimed in time, which will lead to memory overflow, such as the caching mechanism often used in the system. Memory leaks in Java, unlike forgetting to delete in C++, are usually caused by logical causes.

There are three most common OOM situations

java.lang.OutOfMemoryError: Java heap space ——> Java heap overflow. This is the most common situation. It is usually caused by a memory leak or an improper heap size setting. The heap size can modify Java virtual machine parameters. Lang. OutOfMemoryError: PermGen space ——> Java permanent generation overflow, usually occurs in class or JSP pages, or cglib reflection mechanism, because the above situation will produce a large amount of class information storage and method area, this situation can be solved by changing the method area size. Too much string constants especially things also can lead to overflow Java method area. Lang, StackOverflowError — — — — — – > not throw OOM error, but it is also more common Java memory leak, the Java virtual machine, Usually due to the existence of infinite loop or deep recursive call in the program, the stack is too small will also appear this overflow, can be set through the virtual machine parameters

What are the common tuning parameters for the Jvm?

JVM tuning for Bloggers

1. Location of the JVM

Architecture of the Jvm Class loader 1. The VM has a built-in loader

2. Start the class (root) loader

3. Extend the class loader

4. Application loader

/ * * *@author fjj
 * @date2021/1/22 15:47 * /
public class Demo {
    public static void main(String[] args) {
        Demo demo = new Demo();
        // Get that class
        Class<? extends Demo> aClass = demo.getClass();
        // Retrieve the class that loaded the class
        ClassLoader classLoader = aClass.getClassLoader();
        System.out.println("classLoader = " + classLoader);
        // Fetch up
        System.out.println(classLoader.getParent());
        // Get the root loader onSystem.out.println(classLoader.getParent().getParent()); }}Copy the code

5. Parent delegation mechanism

What is the parent delegate mechanism

When a classloader needs to load a.class file, it first assigns the task to its parent classloader, recurses the operation, and only loads the class itself if the parent classloader does not

Class loaders get categories

BootstrapClassLoader

Write c++, load Java core library Java.*, construct ExtClassLoader and AppClassLoader. Because the bootstrap class loader is involved in the local implementation of the virtual machine, the developer cannot directly obtain the reference to the bootstrap class loader, so it is not allowed to directly operate the ExtClassLoader (standard extended classloader) by reference.

Written in Java to load extension libraries, such as jre in classpath, javax.*, or classes in the java.ext.dir specified location, developers can directly use the standard extension class loader.

AppClassLoader (system class loader)

Written in Java, the directory where the loader resides

CustomClassLoader (CustomClassLoader)

Java written, user-defined class loader, can load the specified path of the class file

The role of the parent delegation mechanism

1. Prevent the same.class from being loaded repeatedly. You can delegate to the top and say, well, once it’s loaded, you don’t have to load it again, so you can keep the data safe

2, ensure that the core.class can not be tampered with, through the delegate method, will not be tampered with the core.class, even if tampered will not be loaded, even if loaded will not be the same.class. Different loaders load the same. Class and different calss objects, which ensures class execution security.

The sandbox mechanism

At the heart of the Java security model is the Java sandbox. What is a sandbox? Sandbox is a restricted application environment, the sandbox mechanism is the Java code in the operation of the virtual machine (Jvm) specific scope, and strictly limit access code on the local system resources, through such measures to guarantee the effective separation of code, to prevent damage to the local system, sandbox limited mainly to access system resources, What are the system resources? Cpu, core, file system, network, different levels of sandbox can restrict access to these resources

The basic components of the sandbox

Bytecode validator; Ensuring that Java class files follow the Java language specification can help Java programs achieve memory protection. Not all class files, such as core classes, undergo bytecode verification. Class loaders:

There are three ways in which the classloader works with the Java sandbox. It prevents malicious code from interfering with good faith code. It guards trusted library boundaries. It puts the code in the protected domain and determines what operations the code can do.

Access Controller: The access controller controls the core API’s access to the operating system, and the policy setting for this control can be specified by the user.

The Security Manager is the primary interface between the core AP and the operating system. Implement permission control, superior to the access controller.

Security package: Classes under Java. Security and extension packages that allow users to add new security features to their applications, including:

. Security provider

. The message digest

. A digital signature

. encryption

. To identify

The native keyword

This is a piece of thread code that we see when we click on it

/ * * *@author fjj
 * @date2021/1/24 15:57 * /
public class Demo1 {
    public static void main(String[] args) {
        new Thread(()->{},"My thread").start(); }}Copy the code

There are many methods in a Class that have no method body and they all add a keywordThat’s a key word that’s out of the scope of Java, so if you go back and call the underlying C library you go into the native method stack, you call the native interface the native interface function extends the use of Java, merges different programming languages into Java and when Java was born C,C++, cross, you want to stand, You have to have a program that calls C, C++ and it has a special marker area in the memory area Native Method Stack registers Native methods and when it finally executes, loads the methods in the local Method library through the local interfacePc register

The program counter Each thread has a program counter, thread is private, is a pointer, pointing to the method area of bytecode (used to store address as an instruction, also the instructions to be executed code) to read the next instruction execution engine, is a very small memory space, almost negligible

Methods area

The method area is shared by all threads. All fields and method bytecodes, as well as some special methods such as constructors and interface functions are defined again. Simply put, all the information about defined methods is stored in this area

Static variables, constants, class information (constructors, interface definitions), run-time constant pools are stored in the method area, but instance variables are stored in the heap, independent of the method area

Stack: data structure

Stack: first in, last in, first out, similar to bucket concept queue: first in, first out pipeline

The process of instantiating simple classes Instantiation of a subclass object

The heap

What does a classloader normally put in the Heap after reading a class file? Class methods, constants, variables, real objects that hold all of our reference types

The figure above is from before Jdk 8, since the permanent storage was changed to meta-space. After studying, 99% of the subjects are temporary subjects

Permanent area

This area is resident in memory and is used to store the Class objects and interface metadata carried by the Jdk itself. This area is used to store the environment or Class information of the Java runtime. There is no garbage collection in this area! Turning off VM virtualisation frees up memory in this area

A startup class, loaded a large number of third-party JAR packages, Tomcat deployed too many applications, a large number of dynamically generated reflection classes, constantly loaded, know the memory is full, will appear in OOM

Before jdk1.6, the permanent generation constant pool is in the method area

Jdk1.7 permanent generation, but slowly degradation, to permanent generation, constant pool in the heap

After jdk1.8Without the permanent generation, the constant pool is in the meta space

/ * * *@author fjj
 * @date2021/1/25 * / to him
public class Hello {
    public static void main(String[] args) {
        // Return the maximum memory that the vm attempted to use
        long maxMemory = Runtime.getRuntime().maxMemory();
        // Return the total initial memory of the JVM
        long totalMemory = Runtime.getRuntime().totalMemory();
        // Convert the output to MB
        System.out.println("MaxMemory bytes ="+maxMemory+"\t" +(maxMemory/(double)1024/1024) +"MB");
        System.out.println("TotalMemory bytes =" +totalMemory+"\t"+ (totalMemory/(double)1024/1024) +"MB"); }}Copy the code

We can set parameters for the JVM Set the maximum and minimumGarden of Eden, wrong!! Monitor with Jprofiler tool1, download the plug-in in idea2. Download the EXE file of the client

Jprofiler You can choose the version, I chose 9.1.1 installation is a foolproof installation in ideaWhen used, the following code causes an OutOfMemoryError

import java.util.ArrayList;
import java.util.Random;

/ * * *@author fjj
 * @date2021/1/25 as * /
public class Textoom {

    public static void main(String[] args) {
        String fjj="Fengjiaojiao";
        while (true){
        fjj+= fjj+new Random().nextInt(999999999) +new Random().nextInt(999999999) +new Random().nextInt(999999999); }}}Copy the code

In this case, we can set parameters to dumpThis is what you see at the end of the runOpen it with our toolAt this point you can see which line of our code is in trouble

The GC

When the JVM GC is performed, it does not collect all regions in the same way. Most of the time, the new generation GC is collected. There are two types of GC: light GC (normal GC) and heavy GC (global GC).

The algorithm of GC

Reference counting refers to giving each object a reference counter that increments by 1 whenever it is referenced in a place; When the reference is invalidated, the counter is subtracted by 1; An object whose counter value is zero at any time is not likely to be used. This reference counting method is not used by Java

advantages

1, instant garbage collection: In this method, each object always knows whether it is referenced, and when the number of references is 0, the object can immediately link to the free list as if it were free space.

2, the maximum pause time is short.

3, there is no need to look along the pointer

disadvantages

1, the counter value increase or decrease processing is very heavy

2. The calculator takes up a lot of bits.

3. Cumbersome implementation.

4. Circular references cannot be reclaimed.

Replication algorithm

The replication algorithm is to divide the memory space into two pieces by capacity. When this block of memory runs out, the remaining objects are copied to another block, and the used block is cleaned up at once. This causes half of the memory to be reclaimed each time. When allocating memory, there is no need to consider the complex situation such as memory fragmentation. As long as the pointer on the top of the heap is moved, the memory can be allocated in order. The implementation is simple and efficient.

advantages

No memory fragments

disadvantages

Waste memory space. To assume 100% survivability (extreme) Best use scenario: When object survivability is low, a new area is created

Tag-scan algorithm

The tag-scan algorithm marks the methods that are not in use, and then scans to remove the untagged ones

advantages

No extra space is needed

disadvantages

Memory fragmentation occurs

Label compression algorithm

In order to prevent the generation of memory fragmentation, moving a live object to a segment of the cost of an additional move

From the memory efficiency: copy algorithm > mark clearance algorithm > mark compression calculation (time complexity) from the memory uniformity of replication algorithm = mark compression algorithm > mark clearance algorithm memory utilization: mark compression algorithm = mark clearance algorithm > copy algorithm

Generational collection algorithm

Since there is no best algorithm, there is only the most suitable algorithm. We can use the generational algorithm young generation: low survival rate: copy algorithm old age: large area, with mark clean + mark compression hybrid implementation

What is the JMM model

1. The Java Memory Model is an abstract concept, not a real one. It describes a set of rules or specifications that define how variables in a program (including instance fields, static fields, and elements that make up array objects) are accessed. The goal is to solve atomicity, visibility (cache consistency), and order problems that exist when multiple threads communicate through shared memory. When each thread is created, the Jvm creates a working memory (also called stack space) for it to store thread-private data. The Java memory model specifies that all variables are stored in live memory. But threads (reading assignment, etc.) to the operation of the variables must be conducted in the working memory, first of all variables from the main memory to copy their working memory space, and operation, the variable operation to complete before you write variables back to main memory, cannot be directly operating variables in main memory, working memory copy copy stored in main memory variables.