Simple Java parent delegation mechanism

Parental delegation mechanism

The Java virtual machine uses the on-demand loading method for class files, which means that when the class needs to be used, its class file will be loaded into the memory to generate class objects, and when the class file of a certain class is loaded, the Java virtual The machine adopts the parental delegation mode, that is, the request is handed over to the parent class for processing. It is a task delegation mode.

working principle

The specific principle is as follows
Insert picture description here

  • If a class loader receives a class loading request, it does not load it first, but delegates the request to the loader of the parent class to execute;
  • If the parent class loader still has its parent class loader, it will further delegate upwards, recursively, and the request will eventually reach the top-level startup class loader;
  • If the parent class loader can complete the class loading task, it returns successfully. If the parent class loader cannot complete the loading task, the child loader will try to load it by itself. This is the parent delegation mode.

Sandbox security mechanism

We customize a String class, but when loading the custom String class, we will use the bootstrap class loader to load first, and the bootstrap class loader will first load java\lang\String in the rt.jar package in jdk during the loading process .class, when the main method in the String class is executed, an error will be reported saying that there is no main method, because the core class of the string in the rt.jar package is loaded, and this class does not have a main method. This can ensure the protection of the java core source code, which is the sandbox security mechanism.

Advantages of the parental delegation mechanism

  • Avoid repeated loading of classes
  • To protect the security of the program, to prevent the core API from being tampered at will. For
    example, a custom class: java.lang.String

Guess you like

Origin blog.csdn.net/qq_33626996/article/details/112849758