当前位置:网站首页>[jvm learning] class loading subsystem

[jvm learning] class loading subsystem

2022-06-12 15:13:00 Aiyouwei

JVM– Class loading subsystem

Overview of class loading subsystem

  • Class loading subsystem is responsible for loading from file system or network class file (class The file has a specific identifier at the beginning of the file )
  • The class loading subsystem is only responsible for class Loading of files , As for whether the class can run, there is an execution engine (Execution Engine) decision
  • The loaded class information is stored in a block of memory called the method area , In addition to class information , The method area will also contain information about the runtime constant pool , It may also include string literals and numeric constants ( This part of the constant information is Class Memory mapping for the constant pool part of the file )
  • An overview of the class loading subsystem is shown below
     Insert picture description here

The process of class loading

 Insert picture description here

Linking process

  • load

    1. Get the binary byte stream of a class through its fully qualified name
    2. Convert the static storage structure represented by the byte stream into the runtime data structure of the method area
    3. Generate a representation of this class in memory java.lang.Class object , As various data access entries for this class in the method area
    • Add : load .class How to file
      • Load directly from the local system
      • Get... Through the Internet , Typical scenario :web applet
      • from zip Read in compressed package , Become the future jar、war The basis of format
      • Runtime compute generation , The most commonly used is dynamic proxy technology
      • Generated from other files , Typical scenario :JSP application
      • Extract... From a proprietary database .class file , Relatively rare
      • Get... From the encrypted file , Typical defense Class The protection of the file against decompilation
  • The three processes of linking

    • verification (verify)
      • The purpose is to ensure class The information contained in the byte stream of the file meets the requirements of the current virtual machine , Make sure the loaded class is correct , It will not harm the security of the virtual machine itself
      • It mainly includes four kinds of verification : File format validation , Metadata validation , Bytecode verification , Symbol reference validation
    • Get ready (Prepare)
      • Allocate memory for a class variable and set the default initial value of the class variable , That's zero ( Class variables are static variables )
      • It does not contain final Embellished static, because final It will be allocated at compile time , The preparation phase will explicitly initialize
      • There is no initialization assigned to instance variables , Class variables are assigned in the method area , And instance variables are assigned to along with the object java In the pile
    • analysis (Resolve)
      • The process of converting a symbolic reference in a constant pool into a direct reference
      • Parsing is often accompanied by JVM Execute after initialization
      • Symbol reference is a set of symbols to describe the referenced target , A direct reference is a pointer directly to the target , Relative offset or an indirect handle to the target
      • Parsing actions are mainly for classes or interfaces 、 Field 、 Class method 、 Interface method 、 Method type, etc , Corresponds to... In the constant pool CONSTANT_Class_info、CONSTANT_Fieldref_info、CONSTANT_Methodref_info etc.
  • initialization (Initialization)

    • The initialization phase is the execution of class constructor methods clinit() The process of
    • The method is javac The compiler automatically collects the assignment actions of all class variables in the class and the statements in the static code block
    • The instructions in the constructor method are executed in the order that the statements appear in the source file
    • clinit() Constructor different from class ( relation : The constructor is from the perspective of virtual machine init())
    • If the class has a parent class ,JVM Will guarantee the subclass clinit() Before execution , Of the parent class clinit() Execution completed
    	public class ClinitTest1 {
          
        static class Father{
          
            public static int A =1;
            static{
          
                A = 2;
            }
        }
    
        static class  Son extends Father{
          
            public static int B= A;
        }
    
        public static void main(String[] args) {
          
            // load Father class , Second, load Son class ,
            System.out.println(Son.B);// 2
        }
    }
    

     Insert picture description here

    • The virtual machine must guarantee a class of clinit() Method is locked synchronously under multithreading , The following is an example
    public class DeadThreadTest {
          
        public static void main(String[] args) {
          
            Runnable r = () -> {
          
                System.out.println(Thread.currentThread().getName()+" Start ");
                DeadThread dead = new DeadThread();
                System.out.println(Thread.currentThread().getName()+" end ");
            };
            Thread t1 = new Thread(r," Threads 1");
            Thread t2 = new Thread(r," Threads 2");
    
            t1.start();
            t2.start();
        }
    }
    class DeadThread{
          
        static {
          
            if(true){
          
                System.out.println(Thread.currentThread().getName()+" Initialize the current class ");
                while(true){
          
    
                }
            }
        }
    }
    

    The output of the above code block is :
    Threads 1 Start
    Threads 2 Start
    Threads 1 Initialize the current class
    When the initialization DeadThread Class time , The cycle did not come out , So class clinit() Method not completed , The system is locked , The second thread cannot execute

Loading phase -- Class loader

  • JVM Supports two types of loaders , These are the boot class recorders (Bootstrap ClassLoader) And user-defined loading classes (User-Defined ClassLoader)
  • conceptually , Custom loader generally refers to a kind of loader customized by developers in the program , and java Virtual machine specification query There is no such definition , It's all derived from abstract classes ClassLoader Class loaders are divided into custom class loaders
  • Regardless of the type of class loader , Our most common class loaders in our programs are always just three , As shown in the figure below :
     Insert picture description here
  • Start class loader ( Boot class loader ,Bootstrap Class Loader)
    • This class uses C/C++ Realization , Nested in JVM Inside
    • It's used to load Java The core of the library , For providing JVM I need
    • Not inherited from java.lang.ClassLoader, No parent class loader
    • Load extension classes and application load classes , And specify their parent loader
    • For safety reasons .BootStrap The boot class loader only loads packages named java,javax,sun Initial class
  • The loader of the virtual machine – Extend the classloader (Extension Class Loader)
    • Java Language writing , from sun.misc.Launcher$ExtClassLoader Realization
    • Derive from ClassLoader class
    • The parent loader is the boot loader
    • from java.ext.dirs Load the class library in the directory specified by the system property , Or from JDK Of the installation directory jre/lib/ext subdirectories ( Extended Directory ) Download the class library , If the user created JAR Put it in this directory , It will also be automatically loaded by the extension class loader
    	String exDirs = System.clearProperty("java.ext.dirs");
    	for (String path : exDirs.split(";")){
          
    	    System.out.println(path);
    	}
    
    		/** * ********** Extend the classloader ********** * D:\Program Files\Java\jdk1.8.0_144\jre\lib\ext * C:\WINDOWS\Sun\Java\lib\ext */
    
  • The loader of the virtual machine — Application class loader ( system class loader ,App Class Loader)
    • Java Language writing , from [email protected] Realization
    • Derive from ClassLoader class
    • The parent class loader is the extension class loader
    • It's responsible for loading environment variables classpath Or system properties java.class.path Specify the class library under the path
    • This class loader is the default class loader selected , Generally speaking ,Java The application class is loaded by it
    • adopt ClassLoader.getSystemClassLoader(); You can get the class loader
    System.out.println("********** Start class loader **********");
    //  obtain bootstrapclassloader Able to load api The path of 
    URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
    for (URL element : urls){
          
        System.out.println(element.toExternalForm());
    }
       
    /** * ********** Start class loader ********** * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/resources.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/rt.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/sunrsasign.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jsse.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jce.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/charsets.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jfr.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/classes */
    
  • User defined class loader
    • Why custom class loaders
      • Isolation loading class
      • Modify how classes are loaded
      • Extended load source
      • Prevent source code leaks
    • User defined simple steps
    1. Developers can inherit abstract classes java.lang.ClassLoader Kind of the way , Implement your own classloader
    2. JDK1.2 Before , When customizing class loaders , Always inherit ClassLoader Class and rewrite loadClass() Method , So as to implement the custom class loading class , stay JDK1.2 It is not recommended that users overwrite loadClass() Method , Instead, it is recommended that the custom class loading logic be written in findClass() In the method
    3. When writing custom class loaders , If there are no overly complex requirements , Can inherit directly URLClassLoader class , In this way, you can avoid writing by yourself findClass() Method and method for obtaining byte code stream , Make the writing of custom class recorder more concise
    //  Get system classloader 
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();      
         System.out.println(systemClassLoader);//[email protected]

        //  Get the top 
        ClassLoader extClassLoader = systemClassLoader.getParent(); //[email protected]
        System.out.println(extClassLoader);

        //  Get the top , Could not get boot class loader 
        ClassLoader parent = extClassLoader.getParent();
        System.out.println(parent); //null

        ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();  // [email protected]
        System.out.println(classLoader);

        // String  Class loads using the bootstrap class loader -- > java The core class loaders of are loaded by the boot class loader 
        ClassLoader classLoader1 = String.class.getClassLoader(); // null
        System.out.println(classLoader1);
原网站

版权声明
本文为[Aiyouwei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010503378926.html