Isolation in the Java class loading system

Source: Internet
Author: User

Isolation in the Java class loading system

Author: shengge Chen

Author Profile

Sheng ge Yi, software engineer, you can contact him through shenggexin@topwaver.com.

Body:

Class search and Loading Problems in Java always appear in front of Java programmers from time to time. This is not a shame. I believe no Java programmer has ever encountered classnotexception, therefore, it is not natural to be surprised when someone else sees that they have made such a mistake. However, if a classnotfoundexception occurs, the person becomes confused, I think you should have a look at the Java class loading system. At the same time, to discuss the isolation between class loaders, we will first briefly introduce the class loading architecture.

1. Java class loading Architecture

The process of loading classes is very simple: Find the class location, and load the byte code of the found Java class into the memory to generate the corresponding class object. Java classloaders are used to implement such a process. JVM does not have more than one classloader. In fact, if you want to, you can make the JVM have countless classloaders, of course, in addition to testing JVM, I cannot think of other purposes. You should have discovered this problem. The class loader itself is also a class and it also needs to be loaded into the memory. Who will load these class loaders, is there always a root? Yes, there is such a root. It is the bootstrap classloader that never comes to an end. why is it so fascinating? Because you cannot catch a little bit of its tail in Java code, even though you can understand its existence all the time, because all the class libraries required by the Java Runtime Environment are loaded by it, and it is a C ++ program, which can be run independently. It can be said that it is the starting point of JVM running, great. After Bootstrap completes its task, it will generate an appclassloader (in fact, the system will also use the extended Class Loader extclassloader, which is used to load classes in the Java Runtime Environment extension package ), this class loader is often used. You can call classloader. getsystemclassloader () is obtained. Assume that the program does not use the classloader-related operation settings or customize the new classloader, all Java classes we write will be loaded by it, it is worthy of respect. The area of the appclassloader search class is the familiar classpath, which must be crossed by beginners. Is there any flashing sensation? Let's name it the class path Class Loader according to its class search range. In the previous assumption, when a new class appears in Java, appclassloader first passes the class to its parent class loader, that is, extion classloader, and asks whether it can load the class, if yes, appclassloader won't do it. Similarly, when the extion classloader is loading, it will first ask its parent class loader. We can see that the class loader is actually a tree structure. Each class loader has its own father. When the class loader loads the class, always let your parent loader load (Dear Elders). If the parent loader cannot load the class, you will load it. If it cannot load it, I'm sorry, it will yell: exception, class not found. It is necessary to mention that when a class fails to be loaded using the class path loader, The noclassdeffoundexception exception is thrown. If you use the custom Class Loader loadclass method or the findsystemclass method of classloader to load the class, if you do not deliberately change it, classnotfoundexception is thrown.

Let's briefly summarize the above discussions:

1. The architecture of the JVM class loader can be viewed as a tree structure.

2. parent class loaders give priority to loading. If the parent classloader fails to load, the system will throw the classnotfoundexception or noclassdeffounderror exception.

So under what circumstances will our class be loaded?

2. How classes are loaded

In Java2, how does JVM load classes? There are two types: Implicit class loading and explicit class loading.

2.1 implicit class loading

Implicit class loading is the most common encoding method:

A B = new ();

If there is no Class A when the program runs this code, the JVM will request to load the class loader of the current class to load the class. The problem is that I have made the Code a little more complicated, but there is still no difficulty. Please think about the JVM loading sequence:

Package test;
Public Class {
Public void static main (string ARGs []) {
B = new B ();
}
}

Class B {C ;}

Class C {}

According to the answer, the class loading sequence is a-> B, and class C is not noticed by JVM. Don't be surprised. Think carefully. This is not the result we need most. Let's take a closer look at the JVM loading sequence. When you use the Java a command to run Class A, JVM will first require the Class A to be loaded by the class path classloader (appclassloader), but only, it does not load other classes (Class B) that appear in Class A, and then it calls the main function in Class A until the statement B = new B () is run, JVM finds that Class B programs must be loaded before they can continue to run, so the class path loader will load class B. Although we can see that Class B has class c Declarations, but it is not an actual execution statement, so it does not load C classes. That is to say, the JVM determines whether to load new classes according to the effective execution statement at runtime, so as to load as few classes as possible, this is different from the compilation class.

2.2 explicit class loading

There are many ways to load the displayed class. We will load the class test. A as an example.

Use the forname method of the class. It can either specify the loader or use the loader that loads the current class. For example:

Class. forname ("test. ");
Its effect and
Class. forname ("test. A", true, this. getclass (). getclassloader ());
Is the same.

Use the class path class to load.

Classloader. getsystemclassloader (). loadclass ("test. ");

This method is often used by a system with a complex class loading architecture.

Thread. currentthread (). getcontextclassloader (). loadclass ("test. ")

Use a custom classloader to load classes

Public class myclassloader extends urlclassloader {
Public myclassloader (){
Super (new URL [0]);
}
}
Myclassloader = new myclassloader ();
Myclassloader. loadclass ("test. ");

Myclassloader inherits the urlclassloader class, which is the class loader in the JDK core package. If the parent class loader is not specified, the class path classloader is its parent class loader, myclassloader does not increase the scope of the class, so it has the same effect as the class path loader.

We already know that the architecture of the Java class loader is tree-like. Multiple class loaders can specify the same class loader as their parent class, each sub-class loader is a branch of the tree structure. Of course, they can have a sub-class loader or a class loader without a parent loader, in this case, the bootstrap Class Loader serves as its implicit parent class. In fact, the bootstrap class loader is the ancestor of all class loaders and also the root of the tree structure. This tree structure and parent loader priority mechanism facilitate the compilation of custom class loaders, at the same time, we can let the Program Load classes as expected. For example, the architecture of the Class Loader of a program is as follows:

 

Figure 2: Structure of the Class Loader of a program

As shown in the figure above, classloadera is a custom class loader and its parent class loader is a class path loader. It has two sub-class loaders: classloaderaa and classladerab, classloaderb is another class loader used by the program. It does not have a parent class loader, but has a subclass loader classloaderbb. You may say, hell, how can my program use such a complicated class loader structure. For the sake of the following discussion, I am Wronged for the moment.

3. Strange isolation

We can easily find that the class loaders AA, AB, AB, BB, AA, and B in Figure 2 are located under different branches, and there is no parent-child relationship between them, I don't know how to define this relationship, just say they are located under different branches. Two class loaders in different branches are isolated. This isolation allows instances of two class classes to appear in the memory when they are used to load the same class separately. Because classes loaded by isolated class loaders do not share memory space, it is easy to use a class loader to complete tasks that are impossible, for example, static variables of a class may have multiple values at the same time (although it seems to be of little effect), because even the same static variables of the loaded class will be stored in different memory spaces, for example, if the program needs to use some packages but does not want to be used by other packages of the program, it is very easy to compile a custom class loader. This isolation of the class loader has been well applied in many large software applications and service programs. The following is an example of a static variable of the same class with different values.

Package test;
Public Class {
Public static void main (string [] ARGs ){
Try {
// Define two class loaders
Myclassloader AA = new myclassloader ();
Myclassloader BB = new myclassloader ();

// Use the Class Loader AA to load testb. B
Class clazz = AA. loadclass ("testb. B ");
Constructor =
Clazz. getconstructor (new class [] {INTEGER. Class });
Object object =
Constructor. newinstance (new object [] {New INTEGER (1 )});
Method method =
Clazz. getdeclaredmethod ("printb", new class [0]);

// Use the Class Loader BB to load testb. B
Class clazz2 = BB. loadclass ("testb. B ");
Constructor constructor2 =
Clazz2.getconstructor (new class [] {INTEGER. Class });
Object object2 =
Constructor2.newinstance (new object [] {New INTEGER (2 )});
Method method2 =
Clazz2.getdeclaredmethod ("printb", new class [0]);

// Display the value of the static variable in test. B
Method. Invoke (object, new object [0]);
Method2.invoke (object2, new object [0]);
} Catch (exception e ){
E. printstacktrace ();
}
}
}

 

// Class B must be within the search range of myclassloader,
// It should not be in the search range of the parent class loader of myclassloader.
Package testb;
Public Class B {
Static int B;

Public B (integer testb ){
B = testb. intvalue ();
}

Public void printb (){
System. Out. Print ("My static field B is", B );
}
}

 

Public class myclassloader extends urlclassloader {
Private Static file = new file ("C: // classes ");
// This path stores Class B, but there is no Class

Public myclassloader (){
Super (geturl ());
}

Public static URL [] geturl (){
Try {
Return new URL [] {file. tourl ()};
} Catch (malformedurlexception e ){
Return new URL [0];
}
}
}

The program runs as follows:

My static field B is 1
My static field B is 2

The program results are very interesting. From the programmer's point of view, we can even regard classloaders not in the same branch as different Java virtual machines because they cannot perceive each other's existence. The program should be very careful when using the architecture with Branch class loading to find out the Class search scope of each class loader, avoid classes with the same class name (including the package name and Class Name) in the category search range of the parent and sub-class loaders ), the following example illustrates the problems that may arise from this situation.

Assume that interface A has the same name but different versions,

Version 1:
Package test;
Intefer same {Public String getversion ();}
Version 2:
Package test;
Intefer same {Public String getname ();}

Implementation of two versions of interface:

Implementation of version 1
Package test;
Public class same1impl implements same {
Public String getversion () {return "A Version 1 ";}
}
Implementation of Version 2
Public class same 2 impl implements same {
Public String getname () {return "A Version 2 ";}
}

We still use the Class Loader structure in Figure 2. First, pack the same and same implementation class same1impl of version 1 into the package same1.jar, pack the same and same implementation classes same1impl of version 2 into same2.jar. Now, to do this, put same1.jar into the class search range of the Class Loader classloadera, And put same2.jar into the class search range of the Class Loader classloaderab. When you are eager to run the following seemingly correct program.

In fact, this error is caused by the parent classloader's priority loading mechanism. When the classloader classloaderab loads the same2impl class, it finds that the interface test must be loaded. as a result, the parent class loader is requested to load according to regulations. The parent class loader found test of version 1. the same interface is eager to load, but I cannot think of same2impl as the test of version 2. same, the next thing can be imagined, the exception is thrown.

It is hard to blame that Java does not yet provide a version-differentiated mechanism. If a complicated class loader architecture is used, when multiple versions of a certain package or class appear, special attention should be paid.

Master and flexibly use the architecture of the Java class loader, which is of great help to program system design, program implementation, and program debugging. We hope the above content will help you.

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.