Class loading mechanism for Java

Source: Internet
Author: User
Tags array definition

First, what is the load of a class

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 does not report an error if the class has not been actively used by the program.

Ii. Life cycle of classes

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.

1. Loading: Finding and loading binary data for a class

Loading is the first stage of the class loading process, and during the load phase, the virtual machine needs to complete the following three things:

(1) gets its defined binary byte stream 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) A Java.lang.Class object representing this class is generated 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.

2. Connection

(1) 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.

(2) Preparation: Allocates memory for static variables of the class and initializes it to the default value.

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:

① this time the memory allocation includes only class variables (static), not instance variables, and instance variables are allocated to the Java heap as the object is instantiated when the object is initialized.

② the initial value set here is typically the default value of 0 for the data type (such as 0, 0L, NULL, FALSE, and so on), rather than being explicitly assigned to the value in Java code.

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.

    • Here are a few more points to note:
    • For basic data types, for class variables (static) and global variables, which are used directly 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 does 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 type reference, such as an array reference, an object reference, and so on, if it is not explicitly assigned and is used directly, the system assigns it a default value of 0, or 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.

③ If the Constantvalue attribute is present in the field property sheet 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. We can understand that the static final constant puts its result in the constant pool of the class that called it at compile time.

(3) parsing: Converting 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.

3. Initialization

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:

① specifying an initial value when declaring a class variable

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

JVM initialization steps

① if the class has not been loaded and connected, the program loads and joins the class first.

② if the immediate parent class of the class has not been initialized, its immediate parent class is initialized first.

③ If there are initialization statements in the class, the system executes the initialization statements sequentially.

Class initialization time: Class initialization occurs only when the class is actively used, and the active use of the class includes the following four types:

– Use the New keyword to instantiate an object, read or set a static field for a class (except for a static field that is final decorated), and invoke a static method of a class.

– When a reflection call is made to a class using the methods in the Java.lang.reflect package.

– Initializes a class and discovers that its parent class has not been initialized yet.

– When the virtual machine is started, the virtual machines first initialize the user-specified class that contains the main () method.

The above four cases are called active use , other situations are called passive use , passive use will not cause initialization.

-Initialization Sample Description

The ① subclass refers to the parent class static field (not final) and does not cause subclasses to initialize.

Package Com.demo;class Superclass {    static {        System.out.println ("Super");    }        public static int value = 123;} Class Subclass extends Superclass {    static {        System.out.println ("Sub");}    } public class Testinit {public    static void Main (string[] args) {        System.out.println (subclass.value);}    }

Operation Result:

Super123

Description: The subclass is not initialized, although Subclass.value is used, but the actual subclass inherits the static field of the parent class, and the subclass is not initialized. That is, only classes that have a direct definition of this field will be initialized.

② for classes or interfaces, using their constant fields (final, static) does not cause them to initialize.

Package Com.demo;class Superclass {    static {        System.out.println ("Super");    }        public static final int value = 123;} public class Testinit {public    static void Main (string[] args) {        System.out.println (superclass.value);}    }

Operation Result:

123

Description: A constant of a class or interface does not cause initialization of the class or interface. Because constants are optimized at compile time, they are embedded directly in the bytecode of the Testinit.class file.

③ for classes, initializing subclasses causes the initialization of the parent class (not including the interface).

Package Com.demo;class Superclass {    static {        System.out.println ("Super");    }        public static final int value = 123;} Class Subclass extends Superclass {public    static int i = 3;    static {        System.out.println ("Sub");}    } public class Testinit {public    static void Main (string[] args) {        System.out.println (subclass.i);}    }

Operation Result:

Supersub3

Description: Initializing a subclass causes the initialization of the parent class, and the initialization of the parent class precedes the subclass initialization.

④ refers to a class through an array definition and does not trigger initialization of this class.

Package Com.demo; Class superclass1{public        static int value = 123;        Static    {        System.out.println ("Superclass init");}    } public class testmain{public    static void Main (string[] args)    {        superclass1[] scs = new superclass1[10];< c21/>}}

Run the result as

⑤ for interfaces, initializing a subinterface does not cause the initialization of the parent interface, but only when the parent interface is actually used, such as using constants defined in the parent interface.

4. End of 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

Third, 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 Bootstraploader (boot ClassLoader) 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.

In terms of the Java Virtual machine, there are only two different classloader:

start the ClassLoader: it is implemented in C + + (this is limited to hotspot, the default virtual machine after JDK1.5, and many other virtual machines are implemented in the Java language), which is 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 need to be loaded into memory by the startup ClassLoader before they 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 are also loaded by the ClassLoader, unless the display is loaded with another classloader.

? 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 modifying the class, and the program's modifications will not take effect.

Iv. 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 performed by default;         Use Class.forName () to load the class and specify ClassLoader to initialize without performing static block         //class.forname ("Test2", false, loader);}     }
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 can also control whether static blocks are loaded. And only call the Newinstance () method using the call constructor to create the class object.

Five, 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 ClassLoader load        try {            if (parent! = NULL) {                //If there is a parent ClassLoader, delegate to the parent class loader to load                C = Parent.loadclass (name, false);            } else {                //if the parent class loader does not exist, check whether it is a class loaded by the startup ClassLoader, native class Findbootstrapclass (String name) c = by calling the Local method                FINDBOOTSTRAPCLASS0 (name);            }        } catch (ClassNotFoundException e) {            //If neither the parent ClassLoader nor the startup ClassLoader can complete the load task, the load function of the call itself            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

Class loading mechanism for Java

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.