The purpose of this blog post is to look at two typical problems that may arise when different versions of the same class may be loaded by the JVM. Abstractly speaking, I’m going to examine the following two scenarios in detail:

Two versions of the same class, but originating from different class loaders, come in contact with each other.

There are two versions of the same class available on the class path. Only one gets loaded, but it might be hard to impossible to tell which.

As the last scenario is far more common, I’m going to discuss it first. It often leads to seemingly invalid NoSuchMethodErrors. To understand why that happens, here is how this issue can be reproduced easily:

Create a library, Lib1.jar, that contains exactly this class:

package com.wordpress.mlangc;
public class GoodObject {
}

Create another library, Lib2.jar, that contains an extended version of GoodObject:

the program works just fine. Note that your IDE should allow you to specify the order in which JARs are loaded.

As it is my feeling that example above is rather self explanatory, I won’t elaborate on it in detail. What matters is simply what version GoodObject is found first, and this in turn depends on the order in which your JARs are scanned. While you can easily control the order in this example, things might be far more tricky in a real application. Also note that the order in which JARs in WEB-INF/lib are scanned is undefined as far as I know.

The second issue, namely that two versions of the same class originating from different class loaders come into contact with each other, is less common, but might lead to extremely surprising behavior. I going to demonstrate this on two examples. Both are going to result in a ClassCastException with the seemingly nonsensical error message

The first example uses basic Java only. Compared to the second example it’s extremely artificial (you would normally never do such a thing intentionally or unintentionally), but it shows the issue at hand very clearly. It goes like this:

with GoodLib.jar in your class path. You should see an error message like

Exception in thread "main" java.lang.ClassCastException: com.wordpress.mlangc.GoodObject cannot be cast to com.wordpress.mlangc.GoodObject
at com.wordpress.mlangc.WhenGoodObjectsGoBad.goodObjectFromOtherClassLoader(WhenGoodObjectsGoBad.java:16)
at com.wordpress.mlangc.WhenGoodObjectsGoBad.main(WhenGoodObjectsGoBad.java:10)

Don’t spent too much attention to the code in pathToJarWithGoodObject(). What matters is that we find the path to the JAR that contains GoodObject in a portable manner. This path is then used to construct a second class loader in line 8. Note that I explicitly pass null for the parent class loader. The new class loader is employed to load GoodObject once again, which directly leads to the ClassCastException mentioned above. If you take a look at the relevant parts of the The Java® Virtual Machine Specification it shouldn’t be that surprising that the code above calls for serious trouble. Here is a quote from chapter 5.3. Creation and Loading:

At run time, a class or interface is determined not by its name alone, but by a pair: its binary name (§4.2.1) and its defining class loader.

The cast in line 10 fails, because it attempts to cast a GoodObject originating from a foreign class loader to a GoodObject tied to the class loader that loaded our main class. The error message would be clearer if it included the involved class loaders, but with the necessary background information it’s pretty easy to interpret it the way it is.

Before closing this discussion I want to show you another, more realistic scenario that I’ve actually seen in the wild, where two identical classes are loaded by different class loaders. It involves a custom Tomcat Valve and a simple web application:

Deploy the WAR file you’ve just created into the Tomcat installation you’ve modified before, start the server and try to open a page from the deployed WAR file. Voilà, your browser should now tell you that

Again, the key to this example is that the same class is loaded by different class loaders. The GoodObject in GoodValve is loaded from GoodValve.jar by the Tomcat Common Class Loader while the GoodObject from GoodServlet is loaded by the Webapp Class Loader from the WAR file. Take a look at Tomcat 7 Class Loader HOW-TO if you want to know the gory details.

I recently stumbled over a blog post that explains the usage of Java Anonymous Classes. Not being very happy with the example that was given to show the discussed language feature in action, I left a rather critical comment which I want to explain in more detail:

Tweaking existing classes on the fly is a legitimate use of Java Anonymous Classes. Still, as doing so involves inheritance, the usual rules apply:

The anonymous class should be in a is-a relationship to its parent. This is not true for the LinkedList in the example given here, as the tweaked add method clearly violates the specification of Collection.add(…).

Inheriting from classes that are not designed for inheritance is dangerous, as unlike composition and method invocation, inheritance violates encapsulation. By carelessly inheriting from a random class, you might create strong ties to the implementation of said class without even knowing. Again referring to the queue from here, imagine what would happen if somebody called queue.addAll(…). As it turns out, this very much depends on whether LinkedList.addAll(…) is implemented using LinkedList.add(…) or not, which of course is an implementation detail that is not mentioned in the Javadocs. It might vary between different class library vendors and versions. I strongly recommend reading Items 16 and 17 from Effective Java in this context.

to illustrate a typical use of Java Anonymous Classes for tweaking an existing implementation. The reason for this is that ThreadLocal is designed for inheritance, while LinkedList is not. I know this, because the Javadocs for ThreadLocal contain information for clients who want to extend this class while the Javadocs for LinkedList don’t.

because ThreadNoMore.start() is always executed in thread that invoked it. And if you think that over twice, this should not surprise you at all, as methods are always executed in the thread that invoked them. This even applies to Thread.run(), which is the method we should have overridden instead, but unlike Thread.start(), Thread.run() is normally invoked by the Java Virtual Machine, as the Javadocs for Thread.start() tell us:

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

So apart from not doing what we might have intended, carelessly overriding Thread.start(), that is without calling super.start(), so that the JVM can do its magic, leaves us with a crippled class, that no longer has anything to do with a thread at all. Considering these facts, it should not take you by surprise that

being written to your terminal. As you can see clearly, Thrap.run() is not executed at all, neither from a newly created, nor from the main thread. The fix the code above, you have to call super.start() in Thrap.start() like so: