Better handling of Thread Context ClassLoader in OSGi

omerkudat picture omerkudat · Feb 4, 2010 · Viewed 7.5k times · Source

I've been using OSGi for a while now and I have various solutions to the problems I encountered. I wanted to revisit one of these and see if people had come up with different solutions.

One of the most common issues I have with OSGi (Equinox 3.4.2) is the frequent unavailability of the Thread's context ClassLoader. I know this is partly an Equinox problem, but I have encountered the issue with Felix as well. I encounter this mostly with 3rd party libraries that start their own Threads or ThreadPools. When these are started during Bundle or DS activation, they can end up without their ClassLoader. If the 3rd party library has guards against the context ClassLoader being missing, then no problem, but not everyone checks it. Later, if the said library needs to do dynamic classloading it might blow up.

The idiom I have been using for a while is the following (briefly):

ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    /*
     * Start threads, or establish connections, here, now
     */
} finally {
    Thread.currentThread().setContextClassLoader(tccl);
}

This idiom usually ends up in the Activator or the DS activate() method. There are some minor variations where I do check whether tccl is not null and I don't override the context classloader.

Now, I have a this bit of code plastered into various places where I know some 3rd party library might spawn a Thread and ruin my day. While it was manageable at first, I have ended up having this in many random places and it's bothering me.

Anybody else suffering from this issue, and what solutions have they come up with? I would also like to get an idea of whether this problem is solved in the new Equinox 3.5.x, and whether anyone has actually seen it work?

Regards.

Answer

Ben ODay picture Ben ODay · Jan 18, 2011

Great question, we've been doing the same work around (in Felix/Karaf/Servicemix4.2) and have been searching for a better solution. Here is the response that I got back from the Felix team...

http://old.nabble.com/Can-the-thread-context-classloader-issue-be-solved-at-all--td28260809.html#a30704352

Essentially, they say that there isn't a better solution at the moment.

However, I do see that Equinox references some other options including "Buddy Policies" and using a "Context Finder" here...

http://wiki.eclipse.org/Context_Class_Loader_Enhancements

If anyone knows of other options or even a roadmap to resolve this in the future, please let us know...