views:

36

answers:

2

I'm not entirely sure how I got to this situation but somehow I'm getting a null ClassLoader from Thread.getContextClassLoader. After reading a little (not much info in the docs nor on google) I got the impression that it's valid for the current thread to have a null class loader, and calls to getContextClassLoader should be checked for a null reference.

This is quite surprising since I've seen a couple of open source projects unchecked calls to getContextClassLoader (which got me to checking this in the first place). Specifically, this line in codemodel: JCodeModel.java line 358

(I just verified that log4j doesn't check as well)

So should calls to getContextClassLoader check for a null reference or is something messed up with my threads?

+1  A: 

It's quite valid for Thread.getContextClassLoader to return null. Not all software is of particularly good quality.

Whilst null ClassLoader typically refers to the boot class loader that loads the system classes (I think that's right - the terminology is messed up for historical reasons), for thread context class loaders it is usually interpreted as unset, and the system class loader is used instead.

IIRC, the thread context class loader is set to the system class loader for the main thread if using the java command. For applets the applet thread and EDT have it set to the applet class loader.

I would suggest not using thread context class loaders (or most other thread locals), unless the context requires it.

Tom Hawtin - tackline
Do you happen to know if the context class loader is fixed automatically when native threads are attached to the JVM? I'm not sure how I got to a point where the context class loader is null because everything was working up until now.
Idan K
When a `Thread` is created, it inherits the thread context class loader of the current `Thread`.
Tom Hawtin - tackline
these are native threads, not java threads.
Idan K
@Idan K Then I guess there isn't a current thread to inherit anything from - I am not familiar with how this is implemented in JNI (appears to ignore the constructors, because they would NPE (clearly the first ever thread cannot have a parent)).
Tom Hawtin - tackline
A: 

As Tom says, it is perfectly valid for Thread.getContextClassLoader() to return null. I vaguely recall that the default behaviour has changed over time (or it could have been different in various JVM vendor implementations - I can't remember).

Assuming a non-null context ClassLoader may be valid if you've set one further up the stack and don't have foreign code in between, or if the class/library contract requires one.

As a side note, Class.getClassLoader() can return null too.

McDowell