In my Java classes, I sometimes make use of a ThreadLocal
mainly as a means of avoiding unnecessary object creation:
I think JDK's ThreadPoolExecutor could do ThreadLocals cleaning after task execution but as we know it doesn't. I think it could have provided at least an option. The reason why might be because Thread provides only package private access to its TreadLocal maps, so ThreadPoolExecutor just cannot access them without changing Thread's API.
Interestingly, ThreadPoolExecutor has protected method stubs beforeExecution
and afterExecution
, API says: These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals...
. So I can imagine a Task that implements a ThreadLocalCleaner interface and our custom ThreadPoolExecutor that on afterExecution calls task's cleanThreadLocals();