JVM quick start


1. JVM exploration?

Several interview questions:

1. Would you please talk about your understanding of jvm? Java 8 virtual machine and previous changes update?
2. What is oom? What is stack overflow? How to analyze?
3. What are the common tuning parameters for the jvm?
4. How to capture memory snapshots and analyze Dump files?
5. What do you know about class loader in jvm?

You can enter java -version in cmd to view the version of your virtual machine

2. Where is the JVM?

3. JVM architecture?

JVM tuning is aimed at the method area and heap; Most of the tuning is for the heap

JVM architecture diagram

4. Class loader

Function: the class loader subsystem is responsible for loading class files from the file system or network. Class files have a specific file ID at the beginning of the file.

package com.gd.Jvm;

public class Car {
    //Classes are templates and objects are concrete
    //After entering the JVM, first enter the Class loader classloader - > and then initialize to get the Class object of the Car Class
    public static void main(String[] args) {
        Car car1=new Car();
        Car car2=new Car();
        Car car3=new Car();
        System.out.println(car1.hashCode());
        System.out.println(car2.hashCode());
        System.out.println(car3.hashCode());
		//For different objects, the corresponding Class objects are the same
        Class<? extends Car> aClass1 = car1.getClass();
        Class<? extends Car> aClass2 = car2.getClass();
        Class<? extends Car> aClass3 = car3.getClass();
        System.out.println(aClass1.hashCode());
        System.out.println(aClass2.hashCode());
        System.out.println(aClass3.hashCode());
    }

}


Class loader:

  • Loader of virtual machine
  • Start class loader (root loader)
  • extensions class loader
  • Application Loader (system class loader)
        ClassLoader classLoader = aClass1.getClassLoader();
        System.out.println(classLoader); //sun.misc.Launcher$AppClassLoader@18b4aac2
        System.out.println(classLoader.getParent());//sun.misc.Launcher$ExtClassLoader@1540e19d In jdk/jre/lib/ext
        System.out.println(classLoader.getParent().getParent());//null (1) does not exist (2) java program cannot get

The ClassLoader class obtained by the Application Loader under the java.lang package under the rt.jar package

The extension loader is located in jdk/jre/lib/ext

5. Parental delegation mechanism

Create a java.lang package and create a String class
Override the toString method and call the toString method. An exception occurs
App - > exc - > boot (final execution)
If you look up and find no corresponding loader, you will go down and return to the application loader

package java.lang;

public class String {
    /*
    Parental delegation mechanism: Security
    App ->  Exc  ->  BooT(Final execution)
    1,App Application Loader (AppClassLoader)
    2,Exc Extension class loader
    3,BOOT Start class loader (bootstrap classloader)
     */
    @Override
    public String toString() {
        return "toString";
    }

    public static void main(String[] args) {
        String string =new String();
        String s = string.toString();
        System.out.println(s);
        System.out.println(s.getClass().getClassLoader());

    }

}


eg: create a package again and create a class. The class name is defined as Student and does not have the same name as the class defined in java

package com.gd.Jvm;

public class Student {
    @Override
    public String toString() {
        return "studentString";
    }

    public static void main(String[] args) {
        Student student =new Student();
        String s = student.toString();
        System.out.println(s); //studentString
        System.out.println(s.getClass().getClassLoader());//null
        new  Thread().start();
    }
    /*
    1,The class loader receives a class loading request, Application
    2,Delegate the request upward to the parent class loader to complete it. Delegate upward until the class loader is started
    3,Start the loader to check whether the current class can be loaded. If it can be loaded, it will end. Use the current loader. Otherwise, throw an exception and notify the child loader to load
    4,Repeat step 3
    Class Not Found
    null :JAVA Cannot call ~ c, c++
    Java = C++ :Get rid of cumbersome things, pointers, content management~
    */
}


The thread class calls the start method. If the thread level java cannot handle it, it calls the local method start ()

6. Sandbox security mechanism

Function: prevent malicious code from polluting java source code
Guarded the boundaries of trusted class libraries
The code is classified into the protection domain, which determines what operations the code can perform

For example, we defined a class named String and its package name is Java.lang. because this class originally belongs to the jdk. If there is no sandbox security mechanism, this class will pollute the String in the system. However, due to the sandbox security mechanism, we delegate the boot class loader at the top level to find this class. If not, we delegate it to the extension class loader, No more delegates to the system class loader. However, since String is the jdk source code, it is loaded in the boot class loader. Find it first and use it first, so use the String in the boot class loader. None of the latter can be used, which ensures that it will not be polluted by malicious code.

package com.gd.Jvm;

public class Demo {
    public static void main(String[] args) {
        Demo demo =new Demo();
        demo.test1();
    }
    public void test1(){
        test2();
    }
    public  void test2(){
        test1();
    }
}

Stack overflow

7,Native

1. It will enter the local method stack and call the local method interface JNI
2. JNI function: expand the use of Java and integrate different programming languages for Java, initially C and C++
When Java was born, C and C + + were rampant. If you want to have a foothold, you must have a program calling C and C + +. It specially opened up a marking area in the memory area: Native Method Stack, which is used to register native methods
3. In the final execution, the methods in the local method library are loaded through JNI
4. Java program drives printers and management systems. At present, this method is less and less used, and it is rare in enterprise applications.
5. Now the communication between heterogeneous domains is very developed. Call other interfaces: socket, http

package com.gd.Jvm;

public class Demo1 {
    public static void main(String[] args) {
        new Thread(()->{

        },"hello").start();
    }

    private native void start0();
}

For those with the native keyword, it means that the scope of java cannot be reached. Go back and call the library of the underlying c language

8. PC register (Program Counter Register)

Each thread has a program counter, which is thread private, that is, a pointer to the method bytecode in the method area (used to store the address pointing to an instruction and the instruction code to be executed). When the execution engine reads the next instruction, it is a very small memory space, which can be almost ignored
The pc register is the only one in the jvm that does not overflow the stack

9. Method Area

Method area: static. Final. Class. Constant pool... The constant pool of runtime exists in the method area, but the instance variable exists in heap memory, which is independent of the method area
The method area is shared by all threads, all fields and method bytecodes, and some special methods
Such as construction method and interface code; The information of all defined methods is saved in this area, which belongs to the shared space.

public class Test {
    private  int a;
    private String name="jvmstudy";

    public static void main(String[] args) {
        Test test =new Test();
    }
}

10. Stack

1. Stack is a data structure (last in first out), and queue is a first in first out data structure
2. Why is the main method executed first, but ended last?
The main method is pushed into the stack first and out of the stack last

3. Stack alias: stack memory; Operation of main management procedures; The life cycle is synchronized with the thread. When the thread ends, the stack memory is released,
There is no garbage collection problem
4. Stored in the stack are 8 basic data types, object references and instance methods
5. Stack frame: piece by piece; Press a method into the stack, that is, the stack frame
stack2:; First in to be called
The method being executed is at the top of the stack

Stack, heap, method area relationship

11. Three JVM s

We generally use the HotSpot provided by sun company

BEA
IBM's J9VM

12. Heap

A JVM has only one heap memory, and the size of heap memory can be adjusted

Car car =new Car();
Class<? extends Car> aClass =car.getClass();
//Class loader
ClassLoader classloader = aClass.getClassLoader(); 

After reading the class file, the class loader stores the real objects of the class, methods and constants in the heap. The heap is divided into new area, old area and permanent area
Garbage collection is carried out in the new area, light GC, passing through Eden Park, then entering survival area 0, and then to survival area 1.
If the new area is full, enter the old area and repeat GC
If the aged area is full, enter the permanent storage area
Finally, when the memory is full, OOM will appear, resulting in heap memory overflow error

  • eg: permanent loop, causing OOM error

13. New area, old area and permanent area


Note: general objects are temporary variables
Permanent generation: store class objects, variables, etc. there is no garbage collection
After jdk1.8, the persistent storage area is changed to meta space: logical existence, physical nonexistence
The method area is a constant pool
What should I do when the program is OOM
(1) Expand heap memory and see the results
(2) Analyze the memory and see if there is a problem in that place (professional tools)

1. In a project, when an OOM fault occurs suddenly, how to eliminate the fault and study why it will go wrong?
(1) You can see the errors in the first line of the code. Memory snapshot analysis tools: mat and jpprofiler
(2) Debug, line by line analysis
Functions of MAT and jpprofiler:
Analyze Dump memory files,
Quickly locate memory leaks
2. Why use jpprofiler tools to analyze OOM?
(1) Installing plug-ins in idea
... update later

14. Heap memory tuning

eg:
Default: the total memory allocated is 1 / 4 of the computer memory; The initialized memory is 1 / 64 of the computer memory;

Adjust - Xms527m -Xmx527m -XX:+PrintGCDetails


Turn it down
-Xms1m -Xmx1m -XX:+PrintGCDetails

15,GC

Memory efficiency: copy algorithm > mark removal > mark compression (time complexity)
Memory uniformity: copy algorithm = mark compression > mark removal
Memory utilization: Mark compression = mark clear > copy algorithm
GC Title:
1. The memory model and partition model of the JVM are detailed to what is put in each area?
2. What are the partitions in the heap? Eden, from to, what are the characteristics of the elderly area?
3. What are the algorithms of GC?
Mark clearing method, mark sorting, copy algorithm, reference counter
4. When do light GC and heavy GC occur respectively?

Reference counter

First, each object is assigned a reference counter: the counter itself is consumed

(1) Replication algorithm

From - > to who is empty and who is to
Every GC: the live object of Eden (Eden Park) will be moved to the surviving area. Once Eden area is GC, it will be empty!
Benefit: no memory fragmentation
Disadvantages: wasted memory space: half the space is always to, assuming that the object is 100% alive [extreme case] (relatively dangerous)
Best use scenario: when the object survivability is low: the new area uses the replication algorithm

(2) Mark removal algorithm

(1) Scan these objects and mark the living objects
(2) Clear: clear the unmarked objects
Advantage: no extra space required!
Disadvantages: two scans, a serious waste of time, will produce memory fragments

(3) Compression clearing algorithm

Prevent memory fragmentation, scan again, and move the surviving objects to one end, which increases the moving cost

  • Is there no optimal algorithm?
  • No, only the most appropriate algorithm -- > GC: generational collection algorithm
    Young generation: low survival rate, replication algorithm
    Old age: large area and high survival rate; Mark removal + mark compression hybrid implementation

16,JMM

1. What is JMM?
JAVA memory model is a model built around how to deal with the three characteristics of visibility, atomicity and ordering in the concurrent process.
2. What?
Function: cache consistency protocol is used to define the rules for data reading and writing (abide by and find this rule)
JMM specifies that all variables are stored in Main Memory. Each thread also has its own Working Memory. The Working Memory of the thread stores a copy of the Main Memory of the variables used by the thread. All operations (reading, assignment, etc.) of the thread on the variables must be carried out in the Working Memory, rather than directly reading and writing the variables in the Main Memory (volatile variables still have copies of Working Memory, but because of its special operation sequence, it looks like direct read-write access in Main Memory). Different threads cannot directly access variables in each other's Working Memory, and the value transfer between threads needs to be completed through Main Memory
3. How should he learn?
From the perspective of abstraction, JMM defines the abstract relationship between threads and main memory: shared variables between threads are stored in main memory, and each thread has a private local memory , local memory stores a copy of the thread to read / write shared variables. Local memory is an abstract concept of JMM and does not really exist. Local memory covers cache, write buffer, register and other data storage locations optimized by hardware and compiler

Tags: Java Hadoop jvm kafka

Posted on Mon, 06 Dec 2021 15:16:03 -0500 by Im Jake