JDK-6493635 : (cl) ClassLoader-local variables similar to ThreadLocal
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang:class_loading
  • Affected Version: 6
  • Priority: P5
  • Status: Open
  • Resolution: Unresolved
  • OS: solaris_10
  • CPU: x86
  • Submitted: 2006-11-14
  • Updated: 2017-09-26
Description
A DESCRIPTION OF THE REQUEST :
Often it is useful to associate state with a ClassLoader. For example, references to Class, Field, Method and Constructor should have the same lifetime as the ClassLoader. Currently reloading ClassLoaders either leaks or complicated weak/soft reference mechanisms cause unnecessary work.

I propose an easy to implement class along the lines of ThreadLocal:

package java.lang;
public class ClassLoaderLocal<T> {
    protected T initialValue(ClassLoader loader) { ... }
    public T get(ClassLoader loader) { ... }
    public void set(ClassLoader loader, T value) { ... }
    public void remove(ClassLoader loader) { ... }
    public void removeAll() { ... }
}

JUSTIFICATION :
java.sql.DriverManager leaks. As does java.beans and java.util.logging.Level. Even without reloading ClassLoaders, the soft cache in serialisation can cause disruption of the permanent generation. With reloading, it maintains soft reachability to ClassLoaders. The problem also applies to any third-party software with similar functionality.


CUSTOMER SUBMITTED WORKAROUND :
 o Leak and be damned (the common solution).
 o Use a complicated soft reference solution, potentially hurting performance and causing soft leaks (as serialization).
 o Subclass the interesting ClassLoaders (as AppletClassLoader does for AppContext).
 o Insert a class into the ClassLoader context holding the relevant objects.

Comments
Peter Levart has contributed jdk.internal.loader.ClassLoaderValue class that is used by dynamic proxies and module layer implementation.
2017-09-26