JDK-8081460 : ThreadLocal should have a per-thread close method
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 8u45
  • Priority: P4
  • Status: Resolved
  • Resolution: Duplicate
  • OS: linux
  • CPU: x86
  • Submitted: 2015-05-24
  • Updated: 2015-06-02
  • Resolved: 2015-06-01
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
Theeadlocal is a good idea but can lead to memory leaks when used in a thread pool as there is no defined mechanism for removing all of  the current thread's objects.

JUSTIFICATION :
Avoid more leaks!

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
static ThreadLocal tl = new ThreatLocal;
try {
 // long section that uses tl
} finally {
  tl.close();
}

Developers should NOT have to resort to the brilliant but excessive kludgery shown here:http://www.javaspecialists.eu/archive/Issue229.html

CUSTOMER SUBMITTED WORKAROUND :
http://www.javaspecialists.eu/archive/Issue229.html


Comments
Yes I know but this report is about "a per-thread close method " - which is remove() AFAICS. Heinz's mechanism is as you say completely different. So this report seems somewhat confused to say the least.
01-06-2015

The example in the issue is a little misleading, best to look at Heinz's article on cleaning ThreadLocals. ThreadLocal.remove() only removes "this" thread local. Heinz's article is about removing all thread local values for a given thread. A simplified analogy: it's a bit like the technique developers use to stash and restore a thread context class loader. So the example should be something like: try (new ThreadLocalCleaner()) { // Snapshot thread local values ... // stuff adding new thread local values } // Restore thread local state to the snapshot Used in conjunction with a ThreadPoolExecutor (listening on the before/after execute methods) it's possible to ensure that, for a pool of threads, any thread locals added as a result of executing a runnable do not get left hanging around after the runnable completes.
01-06-2015

What would close() do that ThreadLocal.remove() does not?
01-06-2015

concurrency-interest@cs.oswego.edu is a proper place to discuss this idea.
01-06-2015