Search code examples
javaclassloader

How does the delegation model of class loaders ensure that unique classes are loaded?


I had been reading about the 'uniqueness' feature of the delegation model of class loaders in Java:

https://www.baeldung.com/java-classloaders#uniqueness

I didn't understand, how in the absence of such a model would we run a risk of non-unique classes being loaded?

When class loaders use fully qualified class names to load them, how can we end up loading duplicate classes, specially when we check whether or not a class has been loaded before delegating the task to parent loader?

https://www.baeldung.com/java-classloaders#classloader-work


Solution

  • how can we end up loading duplicate classes, specially when we check whether or not a class has been loaded before delegating the task to parent loader? https://www.baeldung.com/java-classloaders#classloader-work

    The step where the class loader checks whether or not a class has been loaded, i.e. method java.lang.ClassLoader.findLoadedClass, does not imply uniqueness. Imagine two class loaders, CL1 and CL2, both loading a class X. In that case, if CL1 loaded X before CL2, then the check done by CL2 will not return the same class loaded by CL1, because these class loaders do not share this information between them.

    The delegation model is what "shares" this information via the parent class loader.