Java ThreadLocals
ThreadLocals in Java provide an easy way to store variables in a thread. It can be especially convenient when developing a web API — to access a variable anywhere in your code without passing them as arguments. It is used extensively in many java libraries, from logback’s MDC to Spring’s RequestContextHolder, making it easy to access any HTTP request parameters.
However, in a multithreaded environment when using Thread Pools, it can especially be challening to set it up correctly. As you would have to make sure the ThreadLocal object set is inherited by child threads, we also have to ensure to clear the ThreadLocal object after execution of those threads. If a variable in the ThreadLocal is not cleared, another API request could reuse the same thread, taken from the threadpool and access the value from the previous request.
While Spring’s SecurityContextHolder uses InheritableThreadLocal to solve this, there is no fully built in implementation for MDC. Although there are built in functions to make it easy for inheritence, you would have to copy the MDC instance to child threads through the executor via implementing ExecutorService or via other methods that adds this function to your executor.
In the end, if you decide to use ThreadLocals with Thread Pools, extreme care is demanded to avoid unintented side effects.