开发者

Can the thread context class loader be null?

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 th开发者_StackOverflow社区reads?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜