The correct behaviour for a classloader in Java is to:
So the class defined in the system classpath should always get loaded first. Tomcat defines classloader per war, which has the system classloader as a parent, so if you try to load a class, it will first look in the system classpath and then in the classpath defined in the war file.
As per my understanding, this is for two reasons:
So, the question is:
In addition to the above problems, are there any other pitfalls to implementing a classloader which does not do a parent search first?
The parent class loader, in turn, goes through the same process of asking its parent. This chain of delegation continues through to the bootstrap class loader (also known as the primordial or system class loader). If a class loader's parent can load a given class, it returns that class.
Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual Machine) during runtime. They're also part of the JRE (Java Runtime Environment). Therefore, the JVM doesn't need to know about the underlying files or file systems in order to run Java programs thanks to class loaders.
Note: The ClassLoader Delegation Hierarchy Model always functions in the order Application ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap ClassLoader is always given the higher priority, next is Extension ClassLoader and then Application ClassLoader.
In Java, every ClassLoader has a predefined location from where they load class files. There are following types of ClassLoader in Java: Bootstrap Class Loader: It loads standard JDK class files from rt. jar and other core classes.
Tomcat doesn't looks for a parent classloader first. Actually it does the opposite: it first looks in the webapp and only then goes to the parent classloader (which is "lib" for Tomcat 6/7 and "shared" for Tomcat 5.5). The exception for this rule are the system classes (I think everything that has package java.* and javax.*), these classes were looked only in the system classloader. I believe the reason they do it is the #1 reason you stated.
So basically it's ok to implement parent-first strategy. It's also ok to implement parent-last. Both strategies have their cons and pros.
I'll give you one more reason, why to implement parent-first: you reduce the amount of classes loaded in perm memory. Imagine you have multiple web applications using the same library. With parent-first the library with be loaded once. With parent-last it will be loaded multiple times.
However, with parent-first all web-apps will be required to use the same version of the library, while with parent-last they may use different versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With