TSSJS2011: Do You Really Know Class Loaders?

I’m back at The Server Side Java Symposium this year and this is the first breakout session I’m attending.   I think I’ve got good knowledge of ClassLoaders and Java Reflection API, but we’ll see if Jevgeni Kabanov, the speaker, can enlighten me with some new nuggets of knowledge.   He’s Founder & CTO of ZeroTurnaround, a company I know next to nothing about, although I have heard of JRebel, one of their products.   Anyway, enough background info… Let’s jump into the meat of the presentation.

Basics

public class A {
    public void do() {
        B b = new B();
        b.do():
    }
}
Instantiating Object B causes the following:  A.class.getClassLoader().loadClass("B");

Problems & Solutions

1. Class Not Found
You build some code and get a NoClassDefFound exception when deploying and trying to run the servlet.   How do we find out what the problem is?

Some solutions:
* IDE Class Lookup
* find *.jar -exec jar -tf ‘{}’ \; | grep MyClass
* URLClassLoader.getURLs()

2. Wrong Class Found
What if you get a NoSuchMethodError?  What’s happening there?  Well, the Class is found, but there’s something wrong with the class.

Solution:
* Get ClassLoader().getResource(Util2.class.replace(‘.’,’/’) + “.class” to find out where the ClassLoader is getting the class.  Then you can use javap -private Util2 to inspect the contents of the file.

3. More than One Class Found
That error will typically occur if 2 different ClassLoaders are used and find different classes for the same name.   They are not the same.

Helpful:  -verbose:class, as well as ClassLoader.getResource() to identify the different classes.

Leaking ClassLoaders

If a Class has a reference to its ClassLoader, that object has a reference to all of its classes.    To leak a ClassLoader, it’s enough to leak just one object loaded by that ClassLoader.

Hierarchy is not enough?

* Isolation: Difference versions of the same library
* Performance: Class lookup is very slow
* Restricted: Why can’t siblings see each other’s classes?
* OSGI, JBoss, NetBeans and others implement a different system

Follow the speaker on Twitter: @ekabanov