当前位置:网站首页>[jvm learning] parental delegation mechanism and PC register (program counter)

[jvm learning] parental delegation mechanism and PC register (program counter)

2022-06-12 15:13:00 Aiyouwei

Parent delegate mechanism

  • Java Virtual machines are right class The file is loaded on demand , That is to say, only when the class needs to be used will its class File loading into memory generation class object , And loaded into a class class When you file ,Java The virtual machine adopts the two parent delegation mechanism , He leaves the task to the parent class to handle , This is a task delegation mode

working principle

  1. If a class load receives a class load request , Instead of loading it first, it delegates the request to the loader of the parent class to execute
  2. If the loader of the parent class still exists, it will delegate up further , Recursion up in turn , The request will eventually reach the boot class loader
  3. If the parent loader can complete the class loading task , You're back , If the parent class loader cannot complete the load task , The subclass loader will try to load itself , This is the parent delegation mechanism
     Insert picture description here

View source code

  • stay java.lang.ClassLoader.java View the method of loading the class (loadClass)
 protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
    
        synchronized (getClassLoadingLock(name)) {
    
            //  First, check whether the current class has been loaded 
            Class<?> c = findLoadedClass(name);
            if (c == null) {
    
                // c == null  Represents that the current class has not been loaded 
                long t0 = System.nanoTime();
                try {
    
                    //  If there is a parent loader, let the parent loader load 
                    if (parent != null) {
    
                        c = parent.loadClass(name, false);
                    } else {
    
                        //  If the parent loader is empty , Indicates that the class loader has been started (BootStrapClassLoader) 了 
                        //  Start class loader (BootStrapClassLoader) By C/C++ Realized , adopt get It's impossible to get 
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
    
                    //  If the class is not found in the non empty parent loader , Throw out ClassNotFoundException abnormal 
                }
                if (c == null) {
    
                    //  If it is still not loaded , Then try to load the class by yourself 
                    long t1 = System.nanoTime();
                    c = findClass(name);
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
    
                resolveClass(c);
            }
            return c;
        }
    }
  • As you can see from the code above , When a class loads , Do not consider user-defined class loaders , Class will first be in the system class loader (AppClassLoader) Check whether it has been loaded , If you don't need to load . without , Then you'll get the parent loader , Then call the parent loader to extend the class loader (ExtClassLoaderloadClass) Of loadClass. Similarly, in the parent class, you will first check whether you have loaded , If you don't go up to the boot class loader (BootstrapClassLoader). Start class loader on arrival (BootstrapClassLoader) Before , They are all checking whether they have been loaded , You don't choose to load it yourself . Until you start the class loader BootstrapClassLoader, There is no parent loader , At this time, I began to consider whether I could load , If you can't load , Will sink to the child loader to load , All the way to the bottom , If no loader can load , Will throw ClassNotFoundException.

The advantages of the parental delegation mechanism

  • Avoid duplicate loading of classes
  • Protect program security , Prevention core API Be tampered with
    • Custom class :java.lang.String
  • Example
    Customize String class , But loading custom String Class will be loaded first with the loader corresponding to the class , The bootstrap loader will load first during the loading process JDK The documents that come with you (rt.jar In bag java\lang\String.class), At this time, the customized... Is not loaded String class . There is no wrong information main Method , It's because the load is rt.jar In bag java.lang.String There is no in the class main Methodical . So an exception will be thrown . This will ensure that you are right java Protection of core source code , This is the sandbox security mechanism
package java.lang;

public class String {
    
    //  The third stage of initialization 
    static{
    
        System.out.println(" Customize string");
    }
//  error :  In the class  java.lang.String  I can't find it in China.  main  Method ,
    public static void main(String[] args) {
    
        System.out.println("hello,String");
    }
}
/** *  error :  In the class  java.lang.String  I can't find it in China.  main  Method ,  Please put  main  Method is defined as : * public static void main(String[] args) *  otherwise  JavaFX  The application class must extend javafx.application.Application * @param args */

Java Determine if it's the same class

  • stay JVM The middle represents two class There are two necessary conditions for an object to be the same class
    • The complete class name of a class must be consistent , Include package name
    • Load the ClassLoader( finger ClassLoader Instance object ) It has to be the same
  • let me put it another way , stay JVM These two class objects (class object ) From the same Class file , Loaded by the same virtual machine , But as long as they are loaded ClassLoader Instance objects are different , Then the two class objects are not equal

PC register ( Program counter )

  • PC The register is located in the runtime data area ,PC Registers are thread private

  • Jvm Program count register in (Program Count Register), It's about physics PC An abstract simulation of registers

  • effect :PC Registers are used to store the address to the next instruction , Also about to execute the instruction code , The execution engine reads the next instruction
     Insert picture description here

  • It is a small memory space , Almost negligible , It's also the fastest running storage area

  • stay JVM Specification , Each of his threads has its own program counter , Threads are private , The life cycle is consistent with the life cycle of the thread

  • Any time thread has only one method executing , It's called ** The current method ,** The program counter stores what the current thread is executing Java Methodical Jvm Instruction address , Or if it's executing native Method , The value is not specified (undefined)

  • It's an indicator of the flow of program control , Branch 、 loop 、 Jump 、 exception handling 、 Basic functions such as thread recovery rely on this counter

  • When the bytecode interpreter is working , It is to select the next bytecode instruction to be executed by changing the value of the technologist

  • It is the only one in Java Nothing is specified in the virtual machine specification OutotMemoryError Area of situation
     Insert picture description here

  • Use PC The function of register to store bytecode instruction address ( The function of recording the execution address of the current thread )

    • because CPU You need to switch threads all the time , Now, after switching back , You have to know where to start
    • JVM The bytecode interpreter needs to be changed PC Register to determine what bytecode instruction to execute next
  • PC register ( Program register ) Why is thread private

    • In order to accurately record the current bytecode instruction address that each thread is executing , The best way is to assign one to each thread PC register , In this way, each thread can calculate , So that mutual interference will not occur
    • because CPU Limitation of time slice wheel , Multithreading in the concurrent execution process , Any definite moment , A core in a processor or multi-core processor , Only one instruction in a thread will be executed
原网站

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