JVM-tips-loading link initialization, jvm-Tips

Source: Internet
Author: User

JVM-tips-loading link initialization, jvm-Tips

Basic concept: the process of class loading is roughly divided into three stages.
1. loading phase: This phase mainly loads the binary code of the class into the JVM, and carries out the constant pool (class Name, method name, field name), Method Area (Binary bytecode ), stack (local method stack structure), heap (java. lang. class Object.
Three loading classes are available: Bootstrap ClassLoader, which loads classes under jre/lib;
Extension ClassLoader: Load classes under jre/lib/ext;
ApplicationClassLoader: load the class under classpath (the class developed by the application itself, such as the. class file under the project directory/bin)
There is also an extended loading class that meets the special needs of applications. When loading a class, the parent loader takes precedence over the load action. When the parent cannot load the class, the Child class operates.

2. Link phase: There are three phases for verification, preparation, and resolution.
Verification: Implements format and syntax verification for bytecode files.
Preparation: Apply for a bucket for static variables and set the default initial values. For example, private static int a = 2; set a to 0 in preparation;
Resolution: Replace the symbol pointer in the method area with a direct reference.

3. Initialization phase: Initialize static variables, execute static blocks, and create class instances. The above a variable is set to 2 in the initialization phase.

Step 1: Verify the loading + Link (verification, preparation, and resolution) of static variables and static blocks + the change in the value during initialization.

---------------------------------------------------------------------------------

Package com. chong. studyparalell. clazz. loader;

Public class ClassLoaderDemo {
Public static void main (String [] args ){
Test test2 = new Test ();

System. out. println ("Test2 instantiation ends" + test2.toString ());

}
}

Bytes --------------------------------------------------------------------------------------

Package com. chong. studyparalell. clazz. loader;

Public class Test {

Private static Test test1 = new Test ();
Private static int a = 2;
Private static int B = 2;

Static {
System. out. println ("[Test static block] a =" + );
}

Public Test (){

System. out. println ("[Test class constructor] a =" + );
System. out. println ("[Test class constructor] B =" + B );
System. out. println ("[Test class instance]" + this. toString ());
}

Public static Test newInstance (){
Return test1;
}
}

--------------------------------------------------------------------

Log output is as follows:
1 [Test class constructor] a = 0
2 [Test class constructor] B = 0
3 [Test instance] com. chong. studyparalell. clazz. loader. Test @ 16c1857
4 [Test static block] a = 2
5 [Test class constructor] a = 2
6 [Test class constructor] B = 2
7 [Test instance] com. chong. studyparalell. clazz. loader. Test @ 1b1fd9c
8 Test2 instantiation ends com. chong. studyparalell. clazz. loader. Test @ 1b1fd9c

First, the Test class is in the Link stage (preparation stage), and the default value 0 is set for a and B respectively.
After new Test () is executed,
1) initialize the three static variables test1, a, and B of the Test class.
When test1 is initialized, the constructor is called for the first time. At this time, a and B are 0. Corresponding to 1 or 2 lines of logs.
Instantiate test1, 3rd lines of logs.
After test1 is initialized, initialize a, B, and set it to 2.
Then initialize the static block, corresponding to 4th lines of logs.
2) execute the Test class Constructor
Because a and B have been initialized to 2, a and B are output as 2 in the constructor of the execution class. Line 5 and 6 of the log.
Output address information after instantiation, 7th lines of log.
3) In the end, the instance work is completed in the main method, with 8th lines of logs.

-------------------------------------------------------------

 

Step 2: add the parent class and confirm.

-------------------------------------------------------------

Package com. chong. studyparalell. clazz. loader;

Public class TestBase {

Private static int base_a = 2;
Private static int base_ B = 2;

Static {
System. out. println ("[Parent static block] base_a =" + base_a );
}

Public TestBase (){
System. out. println ("[parent class constructor] base_a =" + base_a );
System. out. println ("[parent class constructor] base_ B =" + base_ B );
System. out. println ("[Parent instance]" + this. toString ());
}

}

------------------------------------------------------------------

Package com. chong. studyparalell. clazz. loader;

Public class Test extends TestBase {
The content is the same as the first step;
}

------------------------------------------------------------------

Log output is as follows:

[Parent static block] base_a = 2

[Parent class constructor] base_a = 2

[Parent class constructor] base_ B = 2

[Parent instance] com. chong. studyparalell. clazz. loader. Test @ 19ab8d

[Test class constructor] a = 0

[Test class constructor] B = 0

[Test instance] com. chong. studyparalell. clazz. loader. Test @ 19ab8d

Test static Block a = 2

[Parent class constructor] base_a = 2

[Parent class constructor] base_ B = 2

[Parent instance] com. chong. studyparalell. clazz. loader. Test @ 14 dcfad

[Test class constructor] a = 2

[Test class constructor] B = 2

[Test instance] com. chong. studyparalell. clazz. loader. Test @ 14 dcfad

Test2 instantiation ends com. chong. studyparalell. clazz. loader. Test @ 14 dcfad

It can be found that the static variables, static blocks, and constructor of the parent class are initialized first. Then the static variables of the subclass, static blocks and constructor are initialized.

------------------------------------------------------------------

Step 3: Write a custom Class Loader

------------------------------------------------------------------

Package com. chong. studyparalell. clazz. loader;


Public class MyClassLoaderPilot {

Public static void main (String [] args ){

Try {
MyClassLoader classLoader = new MyClassLoader ();
String filename = "com. chong. studyparalell. demon. DemonThreadDemo ";

Object clazz = classLoader. loadCustomizeClass (filename );
System. out. println (clazz );

} Catch (Exception e ){
E. printStackTrace ();
}
}

}

------------------------------------------------------------------

Package com. chong. studyparalell. clazz. loader;

Import java. io. ByteArrayOutputStream;
Import java. io. FileInputStream;
Import java. io. IOException;

Public class MyClassLoader extends ClassLoader {

Private String demoPath = "D: \ work \ temp \\";

Public Class <?> LoadCustomizeClass (String filename) throws ClassNotFoundException {

FileInputStream FCM = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
Try {
// 1. Get the bytecode of the class file (binary data)
String [] fileNames = filename. split ("\\.");
FS = new FileInputStream (demoPath + fileNames [fileNames. length-1] + ". class ");
Byte [] bytes = new byte [1, 1024];
Int len = 0;
While (len = FCM. read (bytes ))! =-1 ){
Baos. write (bytes, 0, len );
}

} Catch (Exception e ){
Throw new ClassNotFoundException ();
} Finally {
Try {
FCM. close ();
} Catch (IOException e ){
Throw new ClassNotFoundException ();
}
}

Byte [] paramArrayOfByte = baos. toByteArray ();
// 2. Define the binary file as a class Object and return
Return defineClass (filename, paramArrayOfByte, 0, paramArrayOfByte. length );
}
}

------------------------------------------------------------------

The log output is as follows:

Class com. chong. studyparalell. demon. DemonThreadDemo

------------------------------------------------------------------

Actually, let's go through the code again, look at the output of the console, and use your own ideas to perform a virtual follow-up, so you can better understand the class loading process.

See link:

Http://www.cnblogs.com/ityouknow/p/5603287.html

Http://www.cnblogs.com/xiaoxiaohui2015/p/5838674.html

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.