Java ThreadLocal

It is essential to note that ThreadLocal instances are typically private static fields that wish to associate state with a thread (e. g., a user ID or transaction ID). Instance variables don’t need to be defined using ThreadLocal as their values are stored in CPU cache (described more detailed here).

Also, developer must be aware of possible collisions when using ThreadLocals and thread pools together. Consider the following scenario :

  1. First, the application borrows a thread from a pool
  2. Then it stores some thread-confined values into the current thread’s ThreadLocal
  3. Once the current execution finishes, the application returns the borrowed thread to the pool
  4. After a while, the application borrows the same thread to process another request
  5. Since the application didn’t perform any necessary cleanups last time, it may re-use the same ThreadLocal data for the new request

Hence, ThreadLocal values must be removed after thread execution and before returning borrowed thread to a pool. It can be done in two ways :

  • Manual removal of each ThreadLocal once current thread is executed. This decision can be error-prone
  • Extend the ThreadPoolExecutor class and provide a custom hook implementation for beforeExecute() and afterExecute() methods. The thread pool will call the beforeExecute() method before running anything using the borrowed thread. On the other hand, it will call the afterExecute() method after executing logic. See code below :
public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
 
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        // Call remove on each ThreadLocal
    }
}

Previous

Leave a Reply

Your email address will not be published. Required fields are marked *