Parent delegation mechanism
What is class loading
The Javac compiles the.java file into a.class file, and the JVM loads and runs the.class file, which the JVM loads along the way using a classloading ride
Class loader type
- Bootstatp classLoader: the classLoader is implemented by C++. Rt. jar, resources. Jar, charsets. Jar, and class files in %JRE_HOME/lib/.
- Extension ClassLoader (standard Extension ClassLoader) : Inherits URLClassLoader. The corresponding files to be loaded are jar and class in %JRE_HOME/lib/ext
- App ClassLoader (system ClassLoader) : inherits URLClassLoader. All jars and classes in the classpath directory of the loaded application.
- CustomClassLoader (user-defined class loader) : Implemented in Java. We can customize class loaders and load class files in the specified path.
What is the parent delegate mechanism
The parent delegate mechanism is that when a class loader needs to load a.class bytecode file, it first delegates the task to its parent class loader, recurses the operation, and only loads the.class if the parent does not load the.class file.
role
-
Prevent loading the same.class. The delegate asks the parent if the.class has been loaded, and if so, there is no need to reload. Data security is ensured.
-
Ensure that core.class is not tampered with. The core.class will not be tampered with, and even if it is tampered with, it will not be loaded, and even if it is loaded, it will not be the same class object, because different loaders load the same.class object. This ensures safe execution of the Class.
The core code
The core code
protected Class<? > loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loaded Class<? > c = findLoadedClass(name); if (c == null) { long t0 = System.nanoTime(); try { if (parent ! = null) { c = parent.loadClass(name, false); } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. long t1 = System.nanoTime(); C = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; }}Copy the code