Java class loading process

Source: Internet
Author: User

Java class loading process

The lifecycle of a java file from being loaded to being detached takes five phases:

Load-> Link (Verification + preparation + resolution)-> initialize (preparations before use)-> use-> uninstall

Among them, the process of loading (except custom loading) + link is completely the responsibility of jvm, and when to initialize the class (loading + link has been completed before ), jvm has strict rules (in five cases ):

1. When the new, getstatic, putstatic, and invokestatic bytecode commands are run, if the class has not been initialized, initialize it immediately. There are three cases: when a class is instantiated with new, when a static field of the class is read or set (not including static fields modified by final, because they have been inserted into the constant pool) and when the static method is executed.

2. When using the java. lang. reflect. * method to call the class for reflection, if the class has not been initialized, perform the class immediately.

3. When initializing a class, if his father has not been initialized, initialize his father first.

4. When the jvm starts, you need to specify the class of the main class to be executed (including static void main (String [] args), then the jvm will initialize the class first.

5. When Class. forName (String className); is used to load classes, Initialization is also performed. Note: The loadClass (String className) of ClassLoader. The method only loads and compiles a class and does not initialize it.

The preceding five pre-processes are called active references to a class. In other cases, passive references do not trigger class initialization. Here are some examples of passive references:

[Java]
/**
* Passive reference scenario 1
* Referencing static fields of the parent class through subclass does not result in subclass initialization.
* @ Author volador
*
*/
Class SuperClass {
Static {
System. out. println ("super class init .");
}
Public static int values = 123;
}
 
Class SubClass extends SuperClass {
Static {
System. out. println ("sub class init .");
}
}
 
Public class test {
Public static void main (String [] args ){
System. out. println (SubClass. value );
}

}

The output is: super class init 123.

[Java]
/**
* Passive reference scenario 2
* The class is referenced through array references and initialization of this class is not triggered.
* @ Author volador
*
*/
Public class test {
Public static void main (String [] args ){
SuperClass s_list = new SuperClass [10];
}
}

Output Result: No output

[Java]
/**
* Passive reference scenario 3
* Constants are stored in the constant pool of the call class during compilation, and are not referenced in the defined constant class in essence. Therefore, initialization of classes that define constants is naturally not triggered.
* @ Author root
*
*/
Class ConstClass {
Static {
System. out. println ("ConstClass init .");
}
Public final static String value = "hello ";
}
 
Public class test {
Public static void main (String [] args ){
System. out. println (ConstClass. value );
}
}

Output result: hello (tip: at the time of compilation, ConstClass. value has been converted into a hello constant and put into the constant pool of the test class)

The above is for class initialization, and the interface should also be initialized. The interface Initialization is a little different from the class initialization:

The above Code uses static {} to output initialization information, and the interface cannot be implemented, but the compiler still generates a <clinit> () Class constructor for the interface during interface initialization, it is used to initialize the member variables in the interface. This is also done during class initialization. The real difference lies in the third point. Before class initialization is executed, all the parent classes are required to be initialized. However, the initialization of the interface does not seem to catch a bad habit for the initialization of the parent interface. That is to say, the subinterface does not require its parent interface to complete initialization during initialization. It is initialized only when the parent interface is actually used (for example, when a constant on the interface is referenced ).

Next we will break down the entire loading process of the next class: Load-> verify-> prepare-> parse-> initialize

First, load:

This virtual machine must complete three tasks:

1. Get the binary byte stream that defines this class using the full qualified name of a class.

2. Convert 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 that represents the Class in the java heap and serve as the access entry to the data in the method area.

The first point is very flexible. Many technologies are introduced here, because it does not limit where the binary stream comes from:

From the class file-> General file loading

From the zip package-> load classes in jar

From the network-> Applet

..........

Compared with the other stages of the loading process, the loading phase has the strongest controllability, because the class loader can use the system or its own, programmers can write loaders in their own ways to control the acquisition of byte streams.

After obtaining the binary stream, it will be saved in the method area as required by the jvm, and a java. lang. Class object will be instantiated in the java heap to associate with the data in the heap.

After the loading is complete, it is necessary to check the byte streams (in fact, many steps are cross-performed with the above, such as file format verification ):

Purpose: ensure that the byte stream information of the class file conforms to the jvm taste and does not make the jvm feel uncomfortable. If the class file is compiled by pure java code, there will naturally be no unhealthy issues such as array out-of-bounds, jump to a nonexistent code block, because once this phenomenon occurs, the compiler rejects compilation. However, as mentioned earlier, the Class file stream may not be compiled from the java source code, or from the network or other places, you can even write data in hexadecimal notation. If the jvm does not validate the data, some harmful byte streams may cause the jvm to crash completely.

Verification involves several steps: File Format verification-> metadata verification-> bytecode verification-> symbol reference verification

File Format verification: verify whether the byte stream complies with the Class file format specifications and whether the version can be processed by the current jvm version. OK, the byte stream can be saved in the memory method area. The following three verifications are performed in the method area.

Metadata verification: Performs Semantic Analysis on the description of bytecode to ensure that the description complies with the syntax specifications of the java language.

Bytecode test: it is the most complex. It tests the content of the method body to ensure that it does not take anything out of the box during running.

Symbol reference verification: to verify the authenticity and feasibility of some references. For example, if other classes are introduced in the Code, we need to check whether the referenced classes actually exist; or some attributes of other classes are accessed in the code, and the accessible rows of those attributes are verified here. (This step will lay the foundation for subsequent parsing)

The verification phase is important, but not necessary. If some code is repeatedly used and verified for reliability, you can use-Xverify in the implementation phase: none parameter to disable most of the class verification measures, with a short class loading time.

After the above steps are completed, the preparation phase will begin:

This stage allocates memory for class variables (static variables) and sets a stage similar to the initial value, which is allocated in the method area. This step only sets an initial value for those static variables, which are allocated during Object Instantiation. Here, setting the initial value of A Class variable is a little different from assigning a value to a class variable, for example:

Public static int values = 123;

At this stage, the value of value will be 0, rather than 123, because no java code has been executed yet, and 123 is invisible, as we can see, the putstatic command that assigns 123 to value exists in <clinit> () after the program is compiled. Therefore, the value assigned to 123 is executed during initialization.

Here is an exception:

Public static final int value = 123;

Here, the value of the value in the preparation phase is initialized to 123. This means that during the compilation period, javac will generate a ConstantValue attribute for this special value, and at the preparation stage, jm will assign a value for this ConstantValue.

After completing the preceding steps, we need to resolve the issue. Parsing seems to be a conversion of Class fields, methods, and other things, specifically involving the format content of the Class file, not in-depth understanding.

The initialization process is the last step of the class loading process:

In the previous class loading process, in addition to the user's participation in the loading phase through the custom class loader, other actions are completely jvm-dominated, and the initialization phase is reached, to really execute the code in java.

This step will execute some pre-operations. Note that in the preparation phase, the system has assigned a value to the class variable once.

To put it bluntly, this step is the process of executing the <clinit> (); method of the program. Next we will study the <clinit> () method:

<Clinit> () is called the class constructor method, which combines the value assignment of all class variables in the mobile phone class of the compiler with the statements in the static statement block, they are arranged in the same order as in the source file.

<Clinit> (); the method is different from the class constructor. It does not need to be shown to call the <clinit> (); method of the parent class, the virtual opportunity ensures the sub-class <clinit> (); the method has been executed before the execution of the parent class, that is, the first virtual machine to be executed <clinit> (); the method must be java. lang. object Class.

The following is an example:

[Java]
Static class Parent {
Public static int A = 1;
Static {
A = 2;
}
}
Static class Sub extends Parent {
Public static int B =;
}
Public static void main (String [] args ){
System. out. println (Sub. B );
}


First, the static data is referenced in Sub. B, and the Sub class needs to be initialized. At the same time, the Parent class Parent must initialize the action first. After Parent initialization, A = 2, so B = 2; the previous process is equivalent:


[Java]
Static class Parent {
<Clinit> (){
Public static int A = 1;
Static {
A = 2;
}
}
}
Static class Sub extends Parent {
<Clinit> () {// jvm will first execute the method of the parent class.
Public static int B =;
}
}
Public static void main (String [] args ){
System. out. println (Sub. B );
}


<Clinit> (); methods are not required for classes and interfaces. If class variables are not assigned a value in a class or interface and there is no static code block, <clinit> () method will not be generated by the compiler.
Because there cannot be static code blocks such as static {} in the interface, but there may still be variable assignment operations during variable initialization, the <clinit> () constructor will also be generated in the interface. But what is different from the class is that <clinit> () of the sub-interface is executed; <clinit> (); method of the parent interface does not need to be executed before the method, the parent interface is initialized only when the variables defined in the parent interface are used.

In addition, the interface implementation class does not execute the <clinit> (); method during initialization.

In addition, jvm ensures that the <clinit> (); method of a class can be properly locked and synchronized in a multi-threaded environment. <Because Initialization is only executed once>.

The following is an example:

[Java]
Public class DeadLoopClass {
 
Static {
If (true ){
System. out. println ("to be initialized by [" + Thread. currentThread () + "], the following is an infinite loop ");
While (true ){}
}
}

/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
System. out. println ("toplaile ");
Runnable run = new Runnable (){
 
@ Override
Public void run (){
// TODO Auto-generated method stub
System. out. println ("[" + Thread. currentThread () + "] the class to be instantiated ");
DeadLoopClass d = new DeadLoopClass ();
System. out. println ("[" + Thread. currentThread () + "] finished class initialization ");

}; Www.2cto.com

New Thread (run). start ();
New Thread (run). start ();
}
 
}


In this example, blocking occurs during running.

Call ~ First come here'

 

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.