JVM introductory notes, as well as the installation and use of Jprofiler and several common algorithms of GC JMM simple understanding

How
to understand JVM ?
The Jvm java virtual machine is a virtual computer, which is realized by simulating various computer functions on the actual computer. A very important feature of the Java language is that it is platform-independent, and the use of the Java virtual machine is to achieve this The key to the characteristics of the
java8 virtual machine and the previous changes update?
The permanent zone is revoked and the meta-space is referenced:
In the hotSpot virtual machine, when jdk 1.6, the actual team designed the method area as a permanent zone, so that the GC work area can be extended to the method area. This strategy can avoid being a separate method area. design garbage collection mechanism, the downside is that the recovery of the very harsh conditions of the process area, and the results are not good recovery
in jdk1.7 version, the design team is also aware of the problem, but only the method of the string constant pool area permanently removed With
the jdk1.8 version, there is no longer the concept of permanent belt, and the meta space is used to replace the original
rules in the permanent generation meta space: the class and its related metadata in the meta space are consistent with the life cycle of the class loader. Each class loader has a dedicated storage space, it will not reclaim a certain class separately, and the location is also fixed, but when the class loader is no longer alive, all its related space will be removed.
What is OOM?
The full name is "OUT OF Memory", which means that the memory is used up. It comes from the official description of java.lang.OutOfMemoryError Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector This means that when the JVM does not have enough memory to allocate space for the object and the garbage collector has no space to reclaim, it will throw this error (Note: non-exception, because this problem is serious enough to be applied deal with).
Why is there OOM?
1. Less allocated: For example, the memory available for the virtual machine itself (usually specified by the VM parameter at startup) is too small.
2. The application uses too much, and it is used up and not released. If it is wasted, it will cause memory Leak or memory overflow
Memory leak The memory that has been
applied for is confiscated and released, and the virtual machine cannot use the memory again. At this time, the memory leaks. The
memory overflows. The
requested memory exceeds the memory size that the JVM can provide. This is called an overflow

Before using the C language or C++ language, we must personally be responsible for the memory application and release operations. If the memory is applied for, it will not be released when it is used up. For example, if new in C++ is new but there is no delete, there may be a memory leak. Otherwise, it will cause memory overflow.

In the Java language, due to the existence of an automatic garbage collection mechanism, we generally do not need to actively release the memory occupied by unused objects. In theory, there will be no "memory leak", but if the encoding is not appropriate, such as Put the reference of an object in the global MAP, although the method is over, because the garbage collector will reclaim the memory according to the reference of the object, the object cannot be reclaimed in time. This will lead to more situations Memory overflow, such as the caching mechanism often used in the system. Memory leaks in Java, which are different from forgetting to delete in C++, are often caused by logical leaks.

The most common OOM situations are the following three
java.lang.OutOfMemoryError: Java heap space ------>java heap memory overflow, this situation is the most common, generally caused by memory leaks or improper heap size settings, for memory Leak, you need to find the leaked code in the program through the memory monitoring software, and the heap size can be modified through the virtual machine parameters
java.lang.OutOfMemoryError: PermGen space ------>java permanent generation overflow, generally appear in the class or jsp page , Or the case of reflection mechanisms such as cglib, because the above situation will generate a large amount of Class information storage and method areas. This situation can be solved by changing the size of the method area. In addition, too many constants, especially strings, will also lead to the method area. Overflow
java.lang.StackOverflowError ------> OOM error will not be thrown, but it is also a relatively common JAVA memory overflow, Java virtual machine overflow, generally due to the existence of infinite loops or deep recursive calls in the program, the stack is too This kind of overflow can also occur in small
children. What are the common tuning parameters of Jvm that can be set through virtual machine parameters ?
JVM tuning by bloggers

1. Location of JVM
Insert picture description here
Jvm architecture
Insert picture description here
class loader
Insert picture description here
1, virtual machine comes with loader
2, startup class (root) loader
3, extended class loader
4, application loader

/**
 * @author fjj
 * @date 2021/1/22 15:47
 */
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Demo demo = new Demo();
        //获取是那个类得
        Class<? extends Demo> aClass = demo.getClass();
        //获取是那个类加载得这个类
        ClassLoader classLoader = aClass.getClassLoader();
        System.out.println("classLoader = " + classLoader);
        //向上获取
        System.out.println(classLoader.getParent());
        //在上获取到根加载器
        System.out.println(classLoader.getParent().getParent());
    }
}

Insert picture description here
5. Parental delegation mechanism.
What is the parental delegation mechanism.
When a class loader needs to load a certain .class file, it first assigns this task to its superior class loader. This operation is recursive. If the superior class loader is not loaded , I will load the
category
BootstrapClassLoader of this class loader by
c++, load the java core library java.*, construct ExtClassLoader and AppClassLoader. Since the boot class loader involves the local implementation details of the virtual machine, developers cannot directly obtain the reference of the startup class loader, so it is not allowed to directly operate by reference.
ExtClassLoader (standard extended class loader) is
written in java and loads the extended library, such as For
the classes in the specified location of jre, javax.* or java.ext.dir in the classpath, developers can directly use the standard extended class loader.
AppClassLoader (system class loader)
written in java, the directory where the loader is located.
CustomClassLoader (user-defined class loader)
written in java, user-defined class loader, can load the class file of the specified path.
The role of the parent delegation mechanism
1. Prevent Load the same .class repeatedly. Ask the above through delegation. Once loaded, you don’t need to load it again to ensure data security
2. Ensure that core.class cannot be tampered with. Through delegation, core.class will not be tampered with, even if tampered, it will not be loaded. Even if it is loaded, it will not be the same .class. Different loaders load the same .class and not the same calss object, which ensures the safety of class execution.
Sandbox mechanism
The core of the Java security model is the java sandbox. What is a sandbox? The sandbox is an environment that restricts the running of programs. The sandbox mechanism is to set the Java code in the specific operating range of the virtual machine (Jvm), and strictly restrict the code's access to local system resources, and ensure that the code is protected by such measures. Effectively isolate and prevent damage to the local system. The sandbox mainly restricts access to system resources. What does the system resource include? Cpu, kernel, file system, network, different levels of sandbox restrictions on access to these resources can also be different to
form the basic component of the sandbox
bytecode verifier; ensure that java class files follow the java language specification, which can help java The program implements memory protection. But not all class files will undergo bytecode verification, such as core classes.
Class loader: Among them, the class loader plays a role in the java sandbox in three aspects.
It prevents malicious code from interfering with well-intentioned code.
It guards the boundaries of the trusted class library.
It classifies the code into the protection domain and determines what operations the code can perform
.
Access controller: The access controller can control the access rights of the core API to the operating system, and the policy
setting for this control can be specified by the user.
Security manager: It is the main interface between the core AP and the operating system. Realize authority control, which has a higher priority than the access controller
.
Security package (security package): java.security lower classes and lower classes expansion packs, allowing users to add new security for your application
-wide features, including:
. Security provider
. Message summary
. Digital signature
. Encryption
. Identify

native keyword
This is a piece of thread code, we click in and see

/**
 * @author fjj
 * @date 2021/1/24 15:57
 */
public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        new Thread(()->{
    
    },"我的线程").start();
    }
}

Insert picture description here

In a Class class, there are many methods without a method body.
They all add a keyword.
Insert picture description here
This keyword indicates that the scope of java cannot be reached. When you go back and call the underlying C language library, you
will enter the local method stack. Calling the local interface
The role of the local interface extends the use of java and integrates different programming languages ​​for Java.
When java was born, C, C++, and rampant. To gain a foothold, you must have a program
that calls C and C++, which are specially developed in the memory area. A marked area Native Method Stack to register the native method.
In the final execution, the method in the local method library is loaded through the local interface
Insert picture description here
Pc register. The
program counter
Each thread has a program counter, which is private to the thread. It is a pointer to the method. (instruction code address is used to store a pointer to an instruction of image, it is about to be performed) in the region of a method to read the next instruction in the bytecode execution engine, a very small memory space, almost negligible
method area
method The area is shared by all threads. All fields and method bytecodes, as well as some special methods, such as constructors, interface functions are also defined again. Simply put, all the defined method information is stored in this area, and this area belongs to the shared area.
Static variables, constants, class information (construction methods, interface definitions), the runtime constant pool are stored in the method area, but the instance variables are stored in the heap memory, and have nothing to do with the method area

Stack: data structure
Stack: first-in-last-out, last-in-first-out, similar to the concept of buckets
Queue: first-in-first-out pipeline

Simple instantiation process
Insert picture description here
instantiation process subclass object
Insert picture description here
heap
Heap a JVM is only a heap memory, heap memory size can be adjusted
class loader reads the class file, generally what will put the heap? Class methods, constants, variables, save real objects of all our reference types

Insert picture description here
The picture above is before Jdk 8. Later, the permanent storage area was changed to meta space.
After research, 99% of the objects are temporary object
permanent area.
This area is permanent memory. It is used to store the Class object and interface metadata carried by Jdk itself. It stores some environment or class information of Java runtime. This area There is no garbage collection! Turning off VM virtualization will release the memory in this area

A startup class loads a large number of third-party jar packages, Tomcat has deployed too many applications, and a large number of dynamically generated reflection classes are constantly being loaded. When the memory is full, OOM will appear.

Before jdk1.6, the permanent generation constant pool was in the method area
jdk1.7 permanent generation, but slowly degraded, to the permanent generation, the constant pool is in the heap
after jdk1.8, there is no permanent generation, and the constant pool is in the meta space
Insert picture description here

/**
 * @author fjj
 * @date 2021/1/25 14:17
 */
public class Hello {
    
    
    public static void main(String[] args) {
    
    
        //返回虚拟机试图使用的最大内存
        long maxMemory = Runtime.getRuntime().maxMemory();
        //返回jvm 的初始化总内存
        long totalMemory = Runtime.getRuntime().totalMemory();
        //输出转换成MB
        System.out.println("maxMemory字节= "+maxMemory+"\t" +(maxMemory/(double)1024/1024)+"MB");
        System.out.println("totalMemory字节= " +totalMemory+"\t"+ (totalMemory/(double)1024/1024)+"MB");
    }
}

Insert picture description here
We can set the parameters of the jvm,
Insert picture description here
Insert picture description here
set the maximum and minimum
Insert picture description here
Eden, wrong! ! !
Insert picture description here
Use Jprofiler tool to monitor
1, download plug-in
Insert picture description here
2 in idea , download client exe

Jprofiler
Insert picture description here
can choose the version, I chose the 9.1.1
installation is a dumb installation
. Set it in the idea.
Insert picture description here
Use it, the following code will cause OutOfMemoryError

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

/**
 * @author fjj
 * @date 2021/1/25 15:48
 */
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);
}

    }
}

Insert picture description here
When this happens, we can set the parameters first, and dump it.
Insert picture description here
After running, we will see this
Insert picture description here
Insert picture description here
. Open with our tool.
Insert picture description here
Insert picture description here
At this time, we can see which line of our specific code has a problem.
Insert picture description here
GC
jvm is performing GC. , Not uniform recovery of all areas, most of the time, the recovery is the new generation
GC is divided into two types: light GC (ordinary GC) heavy GC (global GC)
GC algorithm,
reference counting method, the
so-called reference counting method It is to give each object a reference counter. Whenever there is a place to reference it, the counter will increase by 1; when the reference is invalid, the value of the counter will decrease by 1; an object whose counter value is 0 at any time is impossible. Used.
The
advantage of this reference counting method that is not used by Java
1. It can recycle garbage instantly: In this method, each object always knows whether it is referenced or not. When the referenced value is 0, the object can immediately treat itself as Make the free space link to the free linked list.

2. The maximum pause time is short.

3. There is no need to look up along the pointer

Disadvantage
1, the increase and decrease processing of the counter value is very heavy

2. The calculator takes up a lot of bits.

3. The implementation is cumbersome.

4. Circular references cannot be recovered.
Copy algorithm The
copy algorithm is to divide the memory space into two pieces according to capacity. When this piece of memory is used up, the surviving objects are copied to another piece, and then the used piece is cleaned up all at once. In this way, half of the memory is reclaimed every time. There is no need to consider complex situations such as memory fragmentation during memory allocation. Just move the pointer at the top of the heap and allocate memory in order, which is simple to implement and efficient to run.
Advantages
No fragmentation of memory
Disadvantages
Waste of memory space. Half of the space is always empty. To assume that the object is 100% alive (extreme situation). The
best use scenario: When the object's survival rate is relatively low, the new area
marking scanning algorithm The
marking scanning algorithm is to first mark the unused methods, and then scan those The
advantages of deleting the unmarked ones.
No extra space is needed.
Disadvantages
. Memory fragmentation.
Marked compression algorithm
is used to prevent the generation of memory fragmentation. Moving the surviving objects to a segment adds a moving cost.

From memory efficiency: Copy algorithm> Mark removal algorithm> Mark compression calculation (time complexity)
From memory neatness, copy algorithm = Mark compression algorithm> Mark clear algorithm
Memory utilization: Mark compression algorithm = Mark clear algorithm> Copy algorithm

Generational collection algorithm
As there is no best algorithm yet, only the most suitable algorithm.
We can use the generational algorithm
Young generation:
low survival rate: replication algorithm
Old generation:
large area, using mark removal + mark compression to achieve
what is JMM model
1, Java memory model (Java memory model) is an abstract concept, It does not really exist. It describes a set of rules or specifications, through which the access methods of various variables in the program (including instance fields, static fields, and elements that constitute an array object) are defined. The purpose is to solve the atomicity, visibility (cache coherency) and order problems that exist when multiple threads communicate through shared memory.
2. The entity of Jvm running program is thread, and when each thread is created, Jvm will create a working memory (also called stack space) for it to store thread private data
3. Java memory model stipulates that all variables are Stored in the living memory, the main memory is a shared memory area, which can be accessed by all threads, but the thread's operations on variables (read assignment, etc.) must be performed in the working memory. First, the variables must be copied from the main memory to their own working memory space. , And then operate on the variable. After the operation is completed, the variable is written back to the main memory. The variable in the main memory cannot be directly manipulated. The copy of the variable in the main memory is stored in the working memory.

Guess you like

Origin blog.csdn.net/m0_46937429/article/details/113041460