java.lang.Thread.contextClassLoader : what if it were a weak reference ? (original) (raw)

Tom Hawtin Thomas.Hawtin at Sun.COM
Mon Mar 23 11:11:39 UTC 2009


Sylvain Laurent wrote:

I'm tracking classloader leaks more or less as a hobby and found out that one of the (many) source of leaks come from threads that still have a reference to a classloader through their contextClassLoader instance variable. So, I'm wondering : what if instead of "private ClassLoader contextClassLoader;" we had "private WeakReference contextClassLoaderRef" and the method getContextClassLoader would more or less returned contextClassLoaderRef.get() ? Would it break many things ? is it incompatible with the specs ?

How much it would break, I wouldn't like to guess.

Incompatible? Yes. It is legitimate to use a class loader only through Thread.getContextClassLoader.

As for solutions: I guess containers could add a fake context class loader with a weak reference to the real one (perhaps parent could optionally become a weak reference?). Really there needs to be more care taken when creating threads to make sure the context class loader (and indeed InheritableThreadLocals) are inherited only when appropriate.

Tom Hawtin



More information about the core-libs-dev mailing list