One, the loading of classes
Class loading refers to reading the binary data in the class's. class file into memory, placing it in the method area of the run-time data area, and then creating a Java.lang.Class object of this class in the heap that encapsulates the class's objects in the method area class. Look at the following 2 figures
The final product loaded by the class is a class object in the heap that encapsulates the data structure of the class within the method area, and provides the Java programmer with an interface to access the data structures within the method area
There are several ways to load classes:
- Load directly from the local system
- Download. class files over the network
- Loading. class files from archive files such as Zip,jar
- Extract the. class file from the proprietary database
- To dynamically compile a Java source file into a. class file (server)
Two, loading steps
The JVM divides the class loading process into three steps: Mount (load), link, and Initialize (Initialize) links are divided into three steps, as shown in:
1. Load: Find and load the binary data of the class; 2. Link:
- Validation: Ensure that the class being loaded is correct
Then why do I have to verify this step? First of all, if the class file generated by the compiler, it certainly conforms to the JVM bytecode format, but in case there is a master to write a class file, let the JVM load and run for malicious purposes, it is not good, so this class file to verify this first pass, If you don't, you won't let it go, it's for security reasons.
3. Initialize: Assigns the correct initial value to the static variable of the class
The preparation phase and initialization phase seems to be a bit contradictory, in fact, is not contradictory, if the class has a statement: private static int a = 10, it is the execution of the process is such, first the bytecode file is loaded into memory, the first link verification this step, verify through the post-preparation phase, to a allocated memory, Because the variable A is static, at this point A is equal to the default initial value of type int 0, that is, a=0, and then to the resolution (said later), to the initialization of this step, the true value of a 10 is assigned to a, at this time a=10
For
1. 静态变量2. 静态初始化块3. 变量4. 初始化块5. 构造器
-
They are initialized sequentially (static variables, static initialization blocks) > (variables, initialization blocks) > constructors
-
Static variables and static initialization blocks are initialized according to the order in which they are defined in the class. Similarly, variables and initialization blocks follow this pattern.
-
Initialization of subclasses is not done until the parent class is fully initialized, and the initialization of the static and static initialization blocks of the subclass is done before the variables of the parent class, initialization blocks, and constructors are initialized.
Three, loader
The class loading of the JVM is done through ClassLoader and its subclasses.
The hierarchy and loading order of a class can be described as:
Verify the principle of the ClassLoader load class:
Test 1: Print the hierarchy of the ClassLoader class, see the following code:
ClassLoader loader = ClassLoaderTest.class.getClassLoader(); //获得加载ClassLoaderTest.class这个类的类加载器 while(loader != null) { System.out.println(loader); loader = loader.getParent(); //获得父类加载器的引用 } System.out.println(loader);
1. Bootstrap ClassLoader
Genga carrier, implemented by C + +, is not a classloader subclass. is the topmost class loader in the Java class loading hierarchy, responsible for loading the core class libraries in the JDK, such as Rt.jar, Resources.jar, Charsets.jar, etc., can be obtained by the following program where the loader loaded the relevant jar or class file:
URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs(); for (int i = 0; i < urls.length; i++) { System.out.println(urls[i].toExternalForm()); }
2. Extension ClassLoader
The extension ClassLoader, which is responsible for loading the Java Extension Class library, loads all the jars under java_home/jre/lib/ext/by default.
3.APP Classloader/system ClassLoader
The Application class loader/system ClassLoader is responsible for documenting the jar packages specified in the Classpath and the class in the directory
4.Custom ClassLoader
The ClassLoader that the application customizes according to its own needs, such as Tomcat and JBoss, will be implemented according to the Java EE specification itself ClassLoader
5. Loading principle
ClassLoader uses a parent-delegate model to search for class
-
Each ClassLoader instance has a reference to the parent ClassLoader (not an inherited relationship, which is a contained relationship)
-
The virtual machine's built-in ClassLoader (Bootstrap ClassLoader) itself does not have a parent classloader, but can be used as a parent ClassLoader for other ClassLoader instances
-
When a ClassLoader instance needs to load a class, it tries to delegate the task to its parent class loader before attempting to search for a class in person.
这个过程是由上至下依次检查的,首先由最顶层的类加载器Bootstrap ClassLoader试图加载,如果没加载到,则把任务转交给Extension ClassLoader试图加载,如果也没加载到,则转交给App ClassLoader 进行加载,如果它也没有加载得到的话,则返回给委托的发起者,由它到指定的文件系统或网络等URL中加载该类。如果它们都没有加载到这个类时,则抛出ClassNotFoundException异常。否则将这个找到的类生成一个类的定义,并将它加载到内存当中,最后返回这个类在内存中的Class实例对象。
6. Overall responsibility
"Overall responsibility" means that when a classloader loads a class, the class that is dependent on and referenced by the class is also loaded by this claddloader unless the other classloader is used by the display.
7. Parental delegation
Parent delegation avoids repeated loading,
When the father has loaded the class, there is no need for the child classloader to be loaded again.
With security in mind, let's just imagine that if you don't use this delegate pattern, we can use a custom string to dynamically replace the type defined in the Java Core API at any time, so there's a huge security risk.
And the way the parents entrust it, you can avoid this situation,
Because the string has been loaded by the Boot class loader (BOOTSTRCP ClassLoader) at startup,
So the user-defined ClassLoader can never load a string of its own writing,
Unless you change the default algorithm for the ClassLoader search class in the JDK.
8.JVM Decision class Same
The JVM determines whether the two classes are the same, not only to determine whether the two class names are the same, but also to determine whether the same class loader instance is loaded.
The JVM considers the two classes to be the same only if the two are both satisfied.
Four, a class of bytecode is only loaded once
- Extclassloader how to ensure that bytecode is loaded only once
逻辑上来说ExtClassLoader的父加载器是Bootstrap,具体到代码,ExtClassLoader继承了URLClassLoader,URLClassLoader继承了类SecureClassLoader,最终一直到抽象类ClassLoader。为了保证“一个类的字节码仅被加载一次”这个目标。ExtClassLoader要做的有两件事: a.保证“ private ClassLoader parent;”正确。(对于ExtClassLoader来说这里为null) b.不要重写“ public Class<?> loadClass(*) throws ClassNotFoundException”方法。
And in the end, it's written in the top abstract class ClassLoader.
Protected synchronized class<?>LoadClass (String name, Boolean resolve) throws ClassNotFoundException {//First,Check if the class has already been loadedclass C =Findloadedclass (name);if (c = = Nullif ( Parent! = Null) {c = Parent.loadclass (name, False FindBootstrapClass0 (Name (classnotfoundexception e Not found, Then invoke Findclass in order//to find the class. C = Findclass (Nameif (Resolve Resolveclass (Creturn C;}
As you can see from the code above, when the class is actually loaded, the child loader recursively calls the parent loader's loadclass (* *) method until it reaches the top level (Parent==null) and calls FINDBOOTSTRAPCLASS0 (* *). If the classnotfoundexception exception is thrown, it means that it has not yet been loaded, and then goes to invoke the specific Findclass (name) to implement the load.
- Appclassloader how to ensure that bytecode is loaded only once
AppClassLoader与ExtClassLoader在保证“一个类的字节码仅被加载一次”这个目标上类似。虽然loadClass方法,但在最后调用了“return super.loadClass(paramString, paramBoolean);”,所以仍旧是OK的。如下所示:
PublicSynchronizedclass loadclass (String paramstring, boolean Paramboolean) throws classnotfoundexception {downloadmanager.getbootclasspathentryforclass (paramstring); int i = paramstring.lastindexof (46); if (i! =-1) {SecurityManager Localsecuritymanager = System.getsecuritymanager (); if (localsecuritymanager! = null) Localsecuritymanager.checkpackageaccess (paramstring.substring (0, i));} return super. Loadclass
Five, customizing your own ClassLoader since the JVM already provides the default ClassLoader, why do you define your own classloader?
Because of the default ClassLoader provided in Java, only the jar and class in the specified directory are loaded, and if we want to load a class or jar from another location,
For example: I'm going to load a class file on the network, and by dynamically loading it into memory, call the methods in this class to implement my business logic.
In this case, the default classloader will not meet our needs, so we need to define our own classloader.
Defining your own ClassLoader is a two-step
The custom ClassLoader needs to inherit the ClassLoader abstract class, overriding the Findclass method, which defines how ClassLoader finds the class.
- Inherit Java.lang.ClassLoader
If we have trouble, we can use or inherit the existing ClassLoader implementations, such as
java.net.URLClassLoaderjava.security.SecureClassLoaderjava.rmi.server.RMIClassLoadersun.applet.AppletClassLoader
Extension ClassLoader and App ClassLoader are all subcategories of java.net.URLClassLoader.
This is the construction method of URLClassLoader:
URLClassLoader(URL[] urls, ClassLoader parent)public URLClassLoader(URL[] urls)
- Overriding the Findclass method of the parent class
If you want to keep your parents delegating the model, you should override the Findclass (name) method, or you can override the LoadClass (name) method if you want to break the parental delegation model.
- findClass:定义查找Class的方式- defineClass:将类文件字节码加载为jvm中的class- findResource:定义查找资源的方式
4.1 Java class Loader