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

Viewed 125

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

2 Answers

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.

Say we have 2 jar files, each containing class com.example.Foo.

Say the jar files are loaded by 2 different classloaders, with loader1 being parent of loader2.

Whether we're running with loader1 or with loader2 as the active classloader, we will always get the class from loader1. The class in the second jar file will never be loaded, hence uniqueness is guaranteed, i.e. we will not have 2 classes with the same name in memory.


FYI: The Servlet specification violates that delegation model, and would load the class from loader2 if it is the active classloader. That has been know to cause trouble, especially with the old Apache Commons Logging library (version 1).

Related