Alex Rivera | Logout

Java classloaders: why search the parent classloader first?

Asked 2011-04-13T13:46:15.387
19

The correct behaviour for a classloader in Java is to:

  1. If it has already been loaded, return the class
  2. Call the parent loadClass()
  3. Try and load the class itself.

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:

  1. To avoid problems with different versions of classes being used. Imagine I redefined java.lang.Object in a war, it would be a nightmare.
  2. To avoid dependencies on child classloaders: The system classloader cannot depend on child classloaders: it would be hard to redeploy a war, for instance.

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?

Edit
Report

2 Answers

2

Tarlog is correct, you don't have to do it that way. Java didn't envision use case like tomcat.

However it is questionable why containers host multiple apps in one VM. Separate processes is nicer.

answered 2011-04-13T14:26:06.850
1

If you do not search your parent at all, you will lose access to all of the standard Java objects, and likely will not be able to run at all.

But it is reasonable to search your own classloader first, before trying the parent. If you want to override behavior that a class above you provides, you would need to do it this way.

The JVM doesn't, because searching your parent first makes the most sense. If you know what you're doing, though, you can do some pretty interesting stuff with class loaders. Take a look at Classworlds.

answered 2011-04-13T14:03:00.450

Your Answer