So you want to be a ClassLoader champion?

It wasn’t until earlier this year when I started learning Scala that I had to venture into how a class was loaded in Java.  It wasn’t that Scala required you to know it, it was simply that they made reference to the Java class path loading basics. I think it was to demonstrate that if you wanted to use Java class, where it would be pulled from and when.

 Previously, at best the only thing I’d had to worry about the order that classes were instantiated and by whom, mainly when sorting out issues of Hibernate either having Lazy cglib instantiations when they were meant to be real classes and vice versa.  A completely different problem but the only time I’ve had to worry about the way objects and classes come to being.

Yesterday while flipping through Head First Design Patterns, I also came across the discussion about Class Loaders when talking about Singletons and having two threads instantiate a Singleton class each and how to avert the problem.

 Today, one of the senior developers was summarising an issue we had at work and mentioned that our custom ClassLoaders used by our webstartable app may have been the cause of the problem.

The universe is asking me to learn about classloaders, hehe….

 So, in short, there are three class loaders in the JVM.

  1. Bootstrap class loader – loads all the classes/jars in the JAVA_HOME/lib directory
  2. Extensions class loader – loads classes/jars in the JAVA_HOME/lib/ext/   (Something reminds me here of the libraries Quicktime would install, and if not, those hooks that Mercury Quicktest Pro would use to get into your java app to automate it)
  3. System class loader – looks at your CLASSPATH variable

So you can make your own classloaders in addition to these.  Wikipedia’s article sights reasons of encryption, rmi, basically any time you need some dynamic class loading :).

 A google search was rich with resources:

JBoss wiki contains a tutorial on ClassLoading

The basics of Java class loaders

OnJava’s article: Internals of Class Loading

Leave a Reply