Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 threads?

like image 787
Idan K Avatar asked Sep 21 '25 00:09

Idan K


1 Answers

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.

like image 70
Tom Hawtin - tackline Avatar answered Sep 22 '25 12:09

Tom Hawtin - tackline