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

前端 未结 5 1238
臣服心动
臣服心动 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:14

    After thinking about this for a year, I've decided it is not acceptable for a JavaEE container to share pooled worker threads between instances of un-related applications. This is not 'enterprise' at all.

    If you're really going to share threads around, java.lang.Thread (in a JavaEE environment, at least) should support methods like setContextState(int key) and forgetContextState(int key) (mirroring setClasLoaderContext()), which permit the container to isolate application-specific ThreadLocal state, as it hands the thread between various applications.

    Pending such modifications in the java.lang namespace, it is only sensible for application deployers to adopt a 'one thread-pool, one instance of related applications' rule, and for application developers to assume that 'this thread is mine until ThreadDeath us do part'.

提交回复
热议问题