JVM Series (i): Java class loading mechanism

Source: Internet
Author: User
Tags object object

Loading mechanism for Java classes

Original: http://www.cnblogs.com/ityouknow/p/5603287.html

1 . What is class loading

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 in the heap that encapsulates the data structure of the class within the method area. The final product loaded by the class is a class object located in the heap, which 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.

The ClassLoader does not need to wait until a class is "first active" and then load it, and the JVM specification allows the ClassLoader to preload it when it is expected that a class will be used. If you encounter a missing or an error in a. class file during pre-loading, the ClassLoader must report an error (Linkageerror error) when the program first actively uses the class, and the class loader will not report an error if the class has not been actively used by the program

How to load A. class file – load directly from the Local system – Download the. class file from the network – load the. class file from an archive file such as Zip,jar – Extract the. class file from the proprietary database – dynamically compile the Java source file into a. class file

2, the life cycle of the class

The process of loading, validating, preparing, parsing, and initializing five stages of the class load. In these five phases, the order in which the four phases of loading, validating, preparing, and initializing occurs is deterministic, and the parsing phase is not necessarily, which in some cases can begin after the initialization phase, in order to support runtime bindings for the Java language (also become dynamic or late bound). Also note that the stages here are started in order, rather than sequentially or in order, because these phases are usually mixed in a cross-section, often invoking or activating another phase during one phase of execution.

? loading : Finding and loading binary data for a class

During the first stage of the load-time class loading process, the virtual machine needs to complete the following three things during the load phase:

1. Get the binary byte stream defined by the fully qualified name of a class.

2. Transform the static storage structure represented by this byte stream into the runtime data structure of the method area.

3. Generate a Java.lang.Class object representing this class in the Java heap as the access entry for the data in the method area.

In contrast to other stages of class loading, the load phase (accurately, the action of getting the binary byte stream of a class during the load phase) is the strongest stage, because developers can either use the system-provided classloader to complete the load or customize their own classloader to complete the load.

When the load phase is complete, the binary byte stream outside the virtual machine is stored in the method area in the format required by the virtual machine, and an object of the Java.lang.Class class is created in the Java heap so that the data in the method area can be accessed through the object.

? Connection

– Validation: Ensure that the class being loaded is correct

Validation is the first step in the connection phase, which is designed to ensure that the information contained in the byte stream of a class file conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine itself. The validation phase will roughly complete the 4-phase inspection action:

file Format Verification : Verify that the byte stream conforms to the specification of the class file format, for example: whether to start with 0xCAFEBABE, whether the major and minor version numbers are within the processing range of the current virtual machine, and whether the constants in the constant pool have unsupported types.

meta-data validation : Semantic analysis of the information described in bytecode (note: Comparing the semantic analysis of the JAVAC compilation phase) to ensure that the information it describes conforms to the requirements of the Java language specification, for example: Whether this class has a parent class, except Java.lang.Object.

bytecode verification : through data flow and control flow analysis, it is reasonable to determine that the program semantics are legal and logical.

symbol Reference Validation : Ensures that parsing actions are performed correctly.

The validation phase is important, but not necessary, and it has no effect on the program runtime, and if the referenced classes are repeatedly validated, consider using the-xverifynone parameter to turn off most of the class validation measures to shorten the load time of the virtual machine class.

– Prepare: Allocate memory for static variables of the class and initialize them to default values

The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables, which are allocated in the method area. There are a few things to note about this phase:

1. This time memory allocation includes only class variables (static), not instance variables, and instance variables are allocated to the Java heap as objects are instantiated when the object is instanced.

2, the initial value set here is usually the default value of the data type 0 (such as 0, 0L, NULL, FALSE, etc.), rather than being explicitly assigned in the Java code value.

Suppose a class variable is defined as: public static int value = 3;

Then the initial value of the variable value after the prep phase is 0, not 3, because no Java method has started executing, and the putstatic instruction that assigns value 3 is stored in the class constructor <clinit> () method after the program is compiled. So an action that assigns value to 3 will not be executed until the initialization stage.

· There are several points to note here: • For basic data types, for class variables (static) and global variables, if they are not explicitly assigned to them, the system assigns them a default value of 0, and for local variables, they must be explicitly assigned before they are used, otherwise the compilation will not pass. Constants that are both static and final modified must be explicitly assigned at the time of declaration, or not at compile time, whereas only final-modified constants can be explicitly assigned at the time of declaration, or they can be explicitly assigned when the class is initialized, in summary, You must assign a value to it explicitly before you use it, and the system does not give it a default value of 0. For reference data types reference, such as array references, object references, and so on, if they are not explicitly assigned and used directly, the system assigns them a default value of 0, which is null. If no values are assigned to elements in the array at initialization, the elements will be given a default value of 0 based on the corresponding data type.

3. If the Constantvalue attribute exists in the field attribute table of the class field, which is both final and static, then in the prepare phase the variable value is initialized to the value specified by the Constvalue property.

Assume that the above class variable value is defined as: public static final int value = 3;

Compile-time Javac will generate the Constantvalue property for value, and in the prepare phase the virtual machine will assign value to 3 based on the settings of Constantvalue. This is the case when you recall the 2nd example of a passive reference to an object in the previous blog post. We can understand that the static final constant puts its result in the constant pool of the class that called it at compile time

– Parse: Convert a symbolic reference in a class to a direct reference

The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference, and the parsing action is primarily for a class or interface, a field, a class method, an interface method, a method type, a method handle, and a call Point qualifier 7 class symbol reference. A symbolic reference is a set of symbols that describe a target, which can be any literal.

A direct reference is a pointer directly to the target, a relative offset, or a handle that is indirectly anchored to the target.

? Initialize

initialization, which assigns the correct initial value to the static variables of the class, the JVM is responsible for initializing the class, primarily initializing the class variables. There are two ways to set the initial value of a class variable in Java:

① declares that a class variable is a specified initial value

② specifying an initial value for a class variable using a static code block

JVM initialization steps

1. If the class has not been loaded and connected, the program loads and connects the class first

2, if the immediate parent class of the class has not been initialized, first initialize its immediate parent class

3, if the class has initialization statements, then the system executes these initialization statements in turn

Class initialization time: The class is initialized only when the class is actively used, and the active use of the class includes the following six types:

– Create an instance of the class, that is, the new way

– Access a static variable for a class or interface, or assign a value to the static variable

– Call the static method of the class

– Reflections (e.g. Class.forName ("Com.shengsiyuan.Test"))

– Initializes a subclass of a class, and its parent class is also initialized

–java a Class (Java Test) that is marked as the startup class when the virtual machine is started, and runs a main class directly using the Java.exe command

End Life cycle

? In the following scenarios, the Java Virtual machine will end the life cycle

– The System.exit () method was executed

– End of normal execution of the program

– the program encountered an exception or error during execution and terminated abnormally

– the Java Virtual machine process terminates due to an operating system error

3. class loader

looking for the ClassLoader, let's start with a small example

Package Com.neo.classloader;public class Classloadertest {public     static void Main (string[] args) {        ClassLoader Loader = Thread.CurrentThread (). Getcontextclassloader ();        SYSTEM.OUT.PRINTLN (loader);        System.out.println (Loader.getparent ());        System.out.println (Loader.getparent (). GetParent ());}    }

After running, the output results:

[email protected] [email protected]NULL

As can be seen from the above results, it is not obtained to Extclassloader's parent Loader, because Bootstrap Loader (boot class loader) is implemented in C language, cannot find a definite way to return the parent Loader, then returns NULL.

The hierarchical relationships of these kinds of loaders are as follows:

Note: The parent loader is not implemented by inheritance, but by combining it.

From the point of view of a Java virtual machine, there are only two different classloader: start the ClassLoader : it uses C + + implementations (this is limited to hotspots, That is, the default virtual machine after JDK1.5, there are many other virtual machines are implemented in the Java language, is a part of the virtual machine itself; all other ClassLoader: These classloader are implemented by the Java language, independent of the virtual machine, and all inherit from the abstract class Java.lang.ClassLoader, which The class loader needs to be loaded into memory by the startup ClassLoader before it can load other classes.

From the Java Developer's point of view, the class loader can be roughly divided into the following three categories:

start the ClassLoader : Bootstrap ClassLoader, which is responsible for loading the jdk\jre\lib (the JDK represents the JDK's installation directory, the same below), or the path specified by the-xbootclasspath parameter, and class libraries that can be recognized by the virtual machine (such as Rt.jar, all classes beginning with java.* are bootstrap ClassLoader loaded). The startup ClassLoader cannot be referenced directly by a Java program.

Extension class loader : Extension ClassLoader, which is implemented by Sun.misc.launcher$extclassloader, is responsible for loading the Dk\jre\lib\ext directory, or all class libraries in the path specified by the JAVA.EXT.DIRS system variable (such as classes beginning with javax.*), developers can use the extension class loader directly.

Application ClassLoader : Application ClassLoader, which is implemented by Sun.misc.launcher$appclassloader, is responsible for loading the class specified by the user class path (ClassPath). Developers can use the ClassLoader directly, if the application does not customize its own classloader, typically this is the default class loader in the program.

Applications are loaded with each other by these three kinds of loaders, and if necessary, we can also add a custom class loader. Because the JVM's own ClassLoader only knows how to load the standard Java class file from the local file system, if you write your own classloader, you can do the following:

1) The digital signature is automatically validated before the non-confidence code is executed.

2) dynamically create custom build classes that meet user-specific needs.

3) Obtain Java class from a specific location, such as in a database and in a network.

JVM class loading mechanism

? overall , when a classloader is responsible for loading a class, other classes that the class relies on and references will also be loaded by the ClassLoader, unless the display uses a different classloader to load

? The parent class Delegate , which first lets the parent ClassLoader attempt to load the class, attempts to load the class from its own classpath only if the parent class loader cannot load the class

? caching mechanism, the caching mechanism will ensure that all the loaded class will be cached, when the program needs to use a class, the class loader first look for the class from the buffer, only the buffer does not exist, the system will read the corresponding binary data, and convert it into a class object and store it in a buffer. This is why the JVM must be restarted after the class has been modified, and the program's modifications will not take effect

4 . Loading of Classes

There are three ways to load a class:

1. When the command line starts the application, it is loaded by the JVM initialization

2. Dynamic loading via Class.forName () method

3. Dynamic loading via Classloader.loadclass () method

Example:

Package Com.neo.classloader;public class Loadertest {public         static void Main (string[] args) throws classnotfoundexception {                 ClassLoader loader = HelloWorld.class.getClassLoader ();                 SYSTEM.OUT.PRINTLN (loader);                 Use Classloader.loadclass () to load the class without executing the initialization block                 loader.loadclass ("Test2");                 Using Class.forName () to load the class, the initialization block//                Class.forName ("Test2") is executed by default;                 Use Class.forName () to load the class and specify ClassLoader, not to execute static block//                Class.forName ("Test2", false, loader) when initializing;}         }

Demo class

The public class Test2 {static         {                 System.out.println ("Static initialization block executed! ");         } }

Switch the loading mode separately, there will be different output results.

Class.forName () and classloader.loadclass () differences

Class.forName (): Loads the class's. class file into the JVM, also interprets the class, and executes the static block in the class;

Classloader.loadclass (): The only thing to do is to load the. class file into the JVM, not to execute the contents of static, only to execute the static block in Newinstance.

Note :

Class.forName (name, initialize, loader) with the parameter function also controls whether static blocks are loaded. And only call the Newinstance () method using the call constructor to create the class object.

5. Parental assignment Model

The workflow of the parent delegation model is that if a classloader receives a request for a class load, it does not attempt to load the class on its own, but instead delegates the request to the parent loader to complete, then up, so that all class load requests should eventually be passed to the top-level startup class loader. The load cannot be completed until the parent loader finds the required class in its search scope, and the child loader tries to load the class on its own.

Parent delegation Mechanism:

1. When Appclassloader loads a class, it first does not attempt to load the class itself, but instead delegates the class load request to the parent ClassLoader Extclassloader to complete.

2. When Extclassloader loads a class, it does not attempt to load the class on its own, but instead delegates the class load request to Bootstrapclassloader to complete.

3, if the Bootstrapclassloader load failure (for example, in $java_home/jre/lib not found in the class), will use the Extclassloader to try to load;

4, if the Extclassloader also failed to load, the Appclassloader will be used to load, if the Appclassloader also failed to load, will report an exception classnotfoundexception.

ClassLoader Source Analysis:

Public class<?> loadclass (String name) throws ClassNotFoundException {return LoadClass (name, false);            } protected synchronized class<?> loadclass (String name, Boolean resolve) throws ClassNotFoundException {            First determine if the type has been loaded Class C = findloadedclass (name); if (c = = null) {//If not loaded, delegate to the parent class to load or delegate to the startup class loader to load the try {if (parent! = NULL                    {//If there is a parent class loader, delegate to the parent ClassLoader to load C = Parent.loadclass (name, false);                        } else {//if the parent class loader does not exist, check whether the class is loaded by the startup class loader by calling the local method native class Findbootstrapclass (String name)                    c = FINDBOOTSTRAPCLASS0 (name);                    }} catch (ClassNotFoundException e) {//If neither the parent ClassLoader nor the startup ClassLoader can complete the load task, call its own load function                c = findclass (name);      }} if (resolve) {resolveclass (c);      } return C; }

Parental delegation Model meaning :

-System class prevents multiple copies of the same byte code in memory

-Ensure safe and stable operation of Java programs

6. Custom class Loader

Typically, we use the System class loader directly. However, sometimes we also need to customize the ClassLoader. For example, the application is to transfer the Java class byte code through the network, in order to guarantee the security, these bytecode has been encrypted processing, then the system ClassLoader cannot load it, so it needs to be implemented by the custom class loader. Custom class loaders are generally inherited from the ClassLoader class, from the above analysis of the LoadClass method, we only need to rewrite the Findclass method. Here we demonstrate the process of customizing the ClassLoader with an example:

Package Com.neo.classloader;import java.io.*;p ublic class Myclassloader extends ClassLoader {private String root; Protected class<?> Findclass (String name) throws ClassNotFoundException {byte[] classdata = loadClassData (NA        ME);        if (Classdata = = null) {throw new ClassNotFoundException ();        } else {return defineclass (name, Classdata, 0, classdata.length);                }} private byte[] loadClassData (String className) {string fileName = root + File.separatorchar        + classname.replace ('. ', File.separatorchar) + ". Class";            try {inputstream ins = new FileInputStream (fileName);            Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();            int buffersize = 1024;            byte[] buffer = new Byte[buffersize];            int length = 0;            while (length = ins.read (buffer))! =-1) {baos.write (buffer, 0, length); } return Baos.tobytearraY ();        } catch (IOException e) {e.printstacktrace ();    } return null;    } public String Getroot () {return root;    public void Setroot (String root) {this.root = root;        } public static void Main (string[] args) {Myclassloader classLoader = new Myclassloader ();        Classloader.setroot ("E:\\temp");        Class<?> TestClass = null;            try {TestClass = Classloader.loadclass ("Com.neo.classloader.Test2");            Object object = Testclass.newinstance ();        System.out.println (Object.getclass (). getClassLoader ());        } catch (ClassNotFoundException e) {e.printstacktrace ();        } catch (Instantiationexception e) {e.printstacktrace ();        } catch (Illegalaccessexception e) {e.printstacktrace (); }    }}

The core of the custom ClassLoader is the acquisition of the bytecode file, and if it is an encrypted bytecode, the file must be decrypted in that class. Since this is just a demonstration, I did not encrypt the class file, so there is no decryption process. Here are a few things to note:

1, the file name passed here needs to be the full-qualified name of the class, that is, the com.paddx.test.classloading.Test format, because the DefineClass method is processed in this format.

2, it is best not to rewrite the LoadClass method, because it is easy to destroy the parental delegation mode.

3, this kind of test class itself can be loaded by the Appclassloader class, so we can not put Com/paddx/test/classloading/test.class under the classpath. Otherwise, due to the existence of the parent delegation mechanism, the class is directly loaded by Appclassloader and not by our custom class loader.

JVM Series (i): Java class loading mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.