Complete JVM learning notes please click here

The JVM architecture diagram

1. Function of class loading subsystem

  • The Class loading subsystem is responsible for loading Class files from the file system or network. Class files have specific file identifiers at the beginning of the file.
  • The ClassLoader is only responsible for loading the class file, and whether it can run is determined by the Execution Engine
  • The loaded class information is stored in a piece of memory called a method area. In addition to Class information, the method area stores runtime constant pool information, possibly including string literals and numeric constants (this constant information is a memory map of the constant pool portion of the Class file)

1.1 ClassLoader Role

1.2 loading

  • The binary byte stream that defines a class is obtained through a class’s fully qualified explicitly;
  • Convert the static storage structure represented by this byte stream to the runtime data of the method area;
  • Generate a java.lang.Class object in memory that represents the Class and acts as an access point for the Class’s various data in the method area

1.3 the link

1.3.1 validation:

  • To ensure that the byte stream in the Class file meets the requirements of the CURRENT VM, ensure that the loaded Class is correct and does not harm vm security.
  • It mainly includes four kinds of verification, file format verification, source data verification, bytecode verification, symbol reference verification.

1.3.2 preparation

  • Allocate memory for class variables and set the default initial value of the class variable, which is zero;
  • Sttic modified with final is not included here, because final is allocated at compile time and initialized explicitly during preparation;
  • Class variables are allocated in the method, and instance variables are allocated in the Java heap along with the object.

1.3.3 parsing

  • The process of converting symbolic references in a constant pool to direct references.
  • In fact, the parsing operation network is followed by the JVM after initialization
  • A symbolic reference is a set of symbols that describe the referenced object. The literal form of symbol application is clearly defined in the Class file format of the Java Virtual Machine Specification. A direct reference is a pointer to a target directly, a relative offset, or a handle to the target indirectly
  • Parsing actions are for classes or interfaces, fields, class methods, interface methods, method types, and so on. CONSTANT_Class_info, CONSTANT_Fieldref_info, and CONSTANT_Methodref_info in the constant pool.

1.4 the initialization

  • The initialization phase is the execution of the class constructor method Clinit ().
  • This method does not need to be defined and is a combination of the statements in the static code block and the assignment actions of all class variables that the Javac compiler automatically collects in a class.We noticed that without the static variable C, there would be no clinit method in the bytecode file
  • Constructor methods execute instructions in the order in which statements appear in the source file
  • Clinit () is different from the constructor of a class. (Correlation: constructor is init() from the virtual machine perspective)
  • If the class has a parent class, the JVM guarantees that the parent class’s Clinit () will complete before the subclass’s Clinit () executes
  • The virtual machine must ensure that a class’s Clinit () method is locked synchronously in multiple threads.

2. Class loader classification

  • The JVM supports two types of loaders, BootStrap classloaders and user-defined classloaders.
  • A custom ClassLoader is conceptually a class of class loaders defined by a developer in a program, but the Java Virtual Machine specification does not define it this way. Instead, it classifies all classloaders derived from the abstract ClassLoader as custom classloaders.
  • No matter how classloaders are classified, the most common class loaders we have in our programs are always just three, as follows:

2.1 Loaders for custom classes and core libraries

  • For user-defined classes: use the system class loader AppClassLoader to load them
  • The Java core class libraries are loaded using the BootStrapClassLoader
Public class ClassLoaderTest {public static void main(String[] args) {public static void main(String[] args) systemClassLoader = ClassLoader.getSystemClassLoader(); System.out.println(systemClassLoader); //sun.misc.Launcher$AppClassLoader18 b4aac2 / / @ get its upper extension class loader this extClassLoader = systemClassLoader. The getParent (); System.out.println(extClassLoader); //sun.misc.Launcher$ExtClassLoader@610455d6 // get its upper layer to get the ClassLoader bootStrapClassLoader = extClassLoader.getParent();
        System.out.println(bootStrapClassLoader); / / null / / for user-defined class: use the system class loader to load this this = ClassLoaderTest. Class. GetClassLoader (); System.out.println(classLoader); //sun.misc.Launcher$AppClassLoader@ 18 b4aac2 / / the String class using the bootstrap class loader to load - > Java core class libraries are using the bootstrap class loader to load this classLoader1 = String. Class. GetClassLoader (); System.out.println(classLoader1); //null } }Copy the code

2.2 Built-in LOADER of VMS

  • ① start the ClassLoader (BootStrap ClassLoader)
    • This class loading is implemented in C/C++ and is nested within the JVM
    • It loads the Java core library (JAVA_HOME/jre/lib/rt. The jar/resources. The jar or sun. Boot. The class. The path under the path of content), is used to provide the JVM itself need to class
    • Does not inherit from java.lang.ClassLoader and has no parent loader
    • Loads extension classes and application classloaders and specifies them as their parent
    • For security reasons, BootStrap starts the class loader to load only classes whose package names start with Java, Javax, and Sun
  • Extension ClassLoader (Extension ClassLoader)
    • Java language, implemented by sun.misc.Launcher$ExtClassLoader.
    • Derived from the ClassLoader class
    • The parent class loader is the initiator class loader
    • Load the class libraries from the directory specified by the java.ext.dirs system property, or from the JRE /lib/ext subdirectory (extension directory) of the JDK installation directory. If user-created jars are placed in this directory, they are automatically loaded by the extension class loader
  • ③ Application class loader (system class loader, AppClassLoader)
    • Java language, implemented by sun.misc.Launcher$AppClassLoader.
    • Derived from the ClassLoader class
    • The parent class loader is the extension class loader
    • It is responsible for loading the class libraries under the path specified by the environment variable classpath or the system property java.class.path
    • The class loader is the default class loader in a program. Generally speaking, Java applications are loaded by it
    • The class loader can be obtained by using the ClassLoader#getSystemClassLoader() method
    Code demo
/** * public class ClassLoaderTest1 {public static void main(String[] args) {system.out.println ()"******** Start class loader *********"); URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs(); / / for BootStrapAPI path that ClassLoader can loadfor(URL e:urls){ System.out.println(e.toExternalForm()); } / / from the above path to choose a class what was in his class loader / / Provider in the/jdk1.8.0 _171. JDK/Contents/Home/jre/lib/jsse jar, The bootstrap class loader to load it this this. = the Provider class. GetClassLoader (); System.out.println(classLoader); //null System.out.println("******** extended class loader ********");
        String extDirs = System.getProperty("java.ext.dirs");
        for (String path : extDirs.split(";")){ System.out.println(path); } / / from the above path to choose a class what was in his class loader: expand the class loader this classLoader1 = CurveDB. Class. GetClassLoader (); System.out.println(classLoader1); //sun.misc.Launcher$ExtClassLoader@4dc63996
    }
}
Copy the code

2.3 User-defined class loaders

why

  • Isolation load class
  • Modify the way classes are loaded
  • Expand the loading source
  • Preventing source code leakage

3 Common methods of ClassLoader and obtaining methods

3.1 ClassLoader class, which is an abstract class, and all subsequent classloaders inherit from ClassLoader (excluding the launcher ClassLoader)

Method names describe
GetParent () Returns the superclass loader for the class loader
LoadClass (String name) Load a Class named name that returns an instance of the java.lang.Class Class
FindClass (String name) Find the Class named name and return an instance of the java.lang.Class Class
FindLoadedClass (String name) Find the loaded Class named name and return an instance of the java.lang.Class Class
DefineClass (String name, byte[] b,int off,int len) Converts the contents of byte array B to a Java Class, returning an instance of the java.lang.Class Class
ResolveClass (Class <? > c) Connects to a specified Java class

3.2 ClassLoader Inheritance Relationship

Extension class loaders and system class loaders inherit indirectly from ClassLoader abstract classes

3.3 How to Obtain ClassLoader

4. Parent delegation

The Java virtual machine loads class files on demand, which means that it loads her class files into an in-memory generated class object when the class needs to be used. In addition, when loading a class file, the Java VIRTUAL machine adopts parental microclap mode, that is, the request is handed over to the parent class, which is a task delegation mode

4.1 Working principle of parent delegation mechanism

case


4.2 Advantages of parent delegation mechanism

  • Avoid reloading classes
  • Protect program security and prevent the core API from being tampered with
    • Custom class: java.lang.string
    • Custom classes: java.lang.MeDsh (the java.lang package requires access, preventing us from customizing classes with package names)

5. Sandbox safety mechanism

Custom String class, but when loading the children of the String class to use the bootstrap loader first load, Jar (Java \lang\String.class). The error message says that there is no main method because rt.jar (Java \lang\ string. class) is loaded. This ensures the protection of the Java core source code, that isSandbox security mechanism.

For example: we can use 360 sandbox when reading and writing usb disk information to prevent viruses in the USB disk from contaminate the system outside the sandbox

6. Other

  • Two necessary conditions in the JVM to indicate whether two class objects exist as the same class
    • The full class name of the class must be consistent, including the package name
    • The ClassLoader (ClassLoader instance object) that loads this class must be the same
  • In other words, in the JVM, even if these two class objects come from the same class file and are loaded by the same virtual machine, they are not equal as long as the ClassLoader instance objects that loaded them are different.

A reference to the class loader

The JVM must know whether a type is loaded by a boot class loader or by a user class loader. If a type is loaded by a user class loader, the JVM stores a reference to that class loader in the method area as part of the session for the type information. When resolving a reference from one type to another, the JVM needs to ensure that the loaders for both types are the same.

Active and passive use of classes

Java programs use classes in active and passive ways

  • Active use, divided into seven situations
    • Create an instance of the class
    • To access or assign a value to a static variable of a class or interface
    • Call a static method of a class
    • Reflection such as class.forname (com.dsh.jvm.xxx)
    • Initialize a subclass of a class
    • Classes that are identified as startup classes when the Java virtual machine starts
    • JDK 7 began to offer a dynamic language support: Java. Lang. Invoke. Analytical results REF_getStatic MethodHandle instance, REF_putStatic, REF_invokeStatic handle corresponding class does not initialize, is initialized
  • Except for these seven cases, any other way of using A Java class is considered a passive use of the class and does not result in class initialization.



JVM learning code and notes

【 code 】 github.com/willShuhuan… JVM_02 Class loading subsystem JVM_03 Run time data area 1- [program counter + vm stack + local method stack] JVM_04 Local method interface JVM_05 Run time data area 2- heap JVM_06 run time data area 3- Method area JVM_07 JVM_08 Execution Engine JVM_09 String constant pool StringTable JVM_10 Garbage Collection 1- Overview + Related algorithm JVM_11 Garbage Collection 2- Concepts related to garbage collection JVM_12 Garbage collection 3- Garbage collector