Home > front end >  Why this class can be loaded twice by Java classloader?
Why this class can be loaded twice by Java classloader?

Time:01-23

This code can load the same class twice by two distinct Classloader.

import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static void main(String[] args) throws Exception {
        URL childAndParentClassesLocation = new URL("file:///C:\\Users\\Machi\\Desktop\\tobeloaded-1.0-SNAPSHOT.jar");
        ClassLoader cl1 = new URLClassLoader(new URL[]{childAndParentClassesLocation}, Main.class.getClassLoader());
        ClassLoader cl2 = new URLClassLoader(new URL[]{childAndParentClassesLocation}, Main.class.getClassLoader());
        Class child1 = cl1.loadClass("example.ToBeLoaded");
        Class child2 = cl2.loadClass("example.ToBeLoaded");
        System.out.println(child2 == child1);
        System.out.println(child2.equals(child1));

    }
}

But a URLClassLoader has the Application ClassLoader as a parent. According to the parent delegation principle, should not the ToBeLoaded class be loaded by the Application ClassLoader once and only once?

CodePudding user response:

If the parent delegation principle is in effect you are right. But that is not always the desired behaviour.

In JEE containers this is per design different. Just imagine two different applications refer to the same class (named mypackage.MyClass). But for some reason one application expects the library 'mypackage' in version 1, while the other in version two. And both of them are incompatible.

Thus JEE containers assign one classloader for each of the applications, and each of them will load that specific version of the class. They reside in memory in parallel, and they are distinct different types, so if you try to cast one into the other you will see an exception raised.

So to really know whether two classes are the same, not only compare their fully qualified class names but also compare the classloader they belong to. I am not aware that at runtime the JVM would check if two classes are the same (content-wise), as it might pop up in your example.

  • Related