Java Parental delegation Model

Source: Internet
Author: User

explanation of the Java Parental delegation model

Before we know the parent delegation model, we have to understand what the ClassLoader is. At the beginning of the virtual machine design team, I wanted the class loading process "to get a binary byte stream that describes the class by fully qualified name of a class." This action can be put into the virtual machine outside the implementation, so that the program itself to decide how to get the class, the implementation of the Code of this action is the class loader.

Maybe a lot of people think that the ClassLoader, as the name implies, is a load class, there is nothing big, but the class loading process is very strict, for any class, we need to load his class loader and the class itself to determine the class in the virtual machine uniqueness. What do you mean?? That is, our virtual confidential comparison of two classes are equal, the precondition is that these two classes must be loaded in the same class loader, if two classes are not loaded by the same loader, then the two classes are necessarily unequal, so there is no comparison of the meaning!

12345678910111213141516171819202122232425262728 public class ClassLoaderTest {    public static void main(String[] args) throws Exception {        ClassLoader myLoader = new ClassLoader() {            @Override            public Class<?> loadClass(String name) throws ClassNotFoundException {                try {                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";                    InputStream is = getClass().getResourceAsStream(fileName);                    if (is == null) {                        return super.loadClass(name);                    }                    byte[] b = new byte[is.available()];                    is.read(b);                    return defineClass(name, b, 0, b.length);                } catch (IOException e) {                    throw new ClassNotFoundException(name);                }            }        };        Object obj = myLoader.loadClass("org.fenixsoft.classloading.ClassLoaderTest").newInstance();        System.out.println(obj.getClass());        System.out.println(obj instanceof org.fenixsoft.classloading.ClassLoaderTest);    }}

  Like the above code, the code is very disappointing to run the results, although the printed classpath is the same, but the result is false, this is why AH? Well, the same path, but the results are different?

This is because we have implemented our own ClassLoader, we have chosen our own load path to load the class, and another class of the same pathname is loaded by another loader (the application ClassLoader ), as long as it is not a class loaded by the same classloader. Must not be the same class!!

Parental delegation Model

From the Java Virtual machine perspective, there are only two different classloader:

(1) A startup class loader, implemented by the C + + language, is part of the virtual machine;

(2) One is all other classloader, these are implemented by Java, independent of the virtual machine outside, inherit from Java.lang.ClassLoader;

But from the developer's point of view , it should be a little more granular, the vast majority of programs are used to the following three types of system-provided ClassLoader:

(1) Start the class loader, the loader is implemented in C + +, it is responsible for loading the class stored in the <java_home>\lib directory, it is only in accordance with the name of the file to identify, the name of the non-conforming class, even if placed in the directory, is no use of eggs .....

(2) Extension class loader, which is responsible for loading the <java_home>\lib\ext directory;

(3) Application class loader, this class is also known as the system ClassLoader, it is responsible for the user class path classpath specified on the class library, developers can directly use the loader;

Applications are loaded with each other by these three loaders, and, if necessary, can also implement their own class loaders, which are the kinds of loader relationships

This hierarchy is what we call the parental delegation model, and it is very intuitive to see that in addition to the top-level startup ClassLoader, the others have their own parent ClassLoader. But here we do not confuse a concept, that is, inheritance (inheritance), this diagram is not an inheritance, but by a combination of the way to achieve up-delegating ....

A parent-delegated workflow is: If a class loader receives a request for a class load, it does not manually load itself immediately (lazy, haha!). ), instead delegate the request to the parent class, each layer is so, to the top layer, then can not be passed up, all the requests are focused on the Startup class loader, when the parent class feedback can not satisfy the request, then the request layer down.

What is the benefit of this? I believe this hierarchy should be clear, but what is the point? For example, Java.lang.Object, he is in the presence of Rt.jar, no matter what kind of loader, is the system comes with or our own implementation, will be the request layer to the top of the delegation, until the start class loader, and start the class loader a look, I have this class, so loaded, so Object in the program's various The class loader is always the same class under load. Conversely, there are no parents to delegate the model, let the various classloader to load themselves, such as our developer wrote the object class, Package name is also Java.lang, then there will be a variety of objects in the system, each level of the class loader loaded its own personality of the object, then as a program in such a fundamental so important object, his uniqueness is not guaranteed, the application will be messy.

The role of the parental delegation model presumably, a lot of people here should be clear and think: Wow! This model is really very powerful ... ". His implementation is also very simple:

12345678910111213141516171819202122 protected synchronized Class<?> loadClass(String name,boolean resolve)throws ClassNotFoundException{    //check the class has been loaded or not    Class c = findLoadedClass(name);    if(c == null){        try{            if(parent != null){                c = parent.loadClass(name,false);            }else{                c = findBootstrapClassOrNull(name);            }        }catch(ClassNotFoundException e){            //if throws the exception ,the father can not complete the load        }        if(c == null){            c = findClass(name);        }    }    if(resolve){        resolveClass(c);    }    return c;}

Code, we can see how this delegation mechanism is implemented, when a loader receives the request, the first will determine whether the current class has been loaded, if not loaded, to start delegating the parent class loader (is so lazy, haha), if there is no parent class, the default use of the Startup class loader. If you throw an exception, it means that the current class loader's parent class can not be loaded, and can not meet the request, then this time only to do their own hands!! So what to do with their own to do the reliable ah haha.

Summarize

Of course, this model has not been mandatory, but recommended that we do so, in previous years there has been a break the mechanism of the event, the Typical example is the Jndi service, his code is given to the startup class loader to implement, but when jndi to centralized management of resources, He needs to invoke the Jndi interfaces that other companies implement and deploy under the classpath of the application, because the code needs to be implemented by our developers themselves, and the class loader does not recognize these classes, and a thread context loader appears. The Jndi service can invoke the loader to load the required code, which is implemented through the parent ClassLoader to request a subclass loader, which has clearly violated the parental delegation model.

Java Parental delegation Model

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.