When should I use a ThreadLocal variable?
How is it used?
ThreadLocal
is useful, when you want to have some state that should not be shared amongst different threads, but it should be accessible from each thread during its whole lifetime.
As an example, imagine a web application, where each request is served by a different thread. Imagine that for each request you need a piece of data multiple times, which is quite expensive to compute. However, that data might have changed for each incoming request, which means that you can't use a plain cache. A simple, quick solution to this problem would be to have a ThreadLocal
variable holding access to this data, so that you have to calculate it only once for each request. Of course, this problem can also be solved without the use of ThreadLocal
, but I devised it for illustration purposes.
That said, have in mind that ThreadLocal
s are essentially a form of global state. As a result, it has many other implications and should be used only after considering all the other possible solutions.