Is it really my job to clean up ThreadLocal resources when classes have been exposed to a thread pool?

前端 未结 5 1229
臣服心动
臣服心动 2021-01-31 14:21

My use of ThreadLocal

In my Java classes, I sometimes make use of a ThreadLocal mainly as a means of avoiding unnecessary object creation:



        
5条回答
  •  生来不讨喜
    2021-01-31 15:15

    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();

提交回复
热议问题