Why do I need the ThreadLocal class in Java?


Explain in general terms what it is and what it is eaten with, and then-maybe a link suitable for an example :)

Author: andreycha, 2017-02-27

2 answers

ThreadLocal - this is a type whose value is different in each thread.

Why would this be necessary? If there are multiple scenarios.

For example, you have an application that uses various libraries and frameworks, the call chain goes very deep, and somewhere there calls your callback. You would like to pass additional information (for example, the rights of the current user, or there is just a cache), but intermediate frameworks do not stretch this additional information through the call chain information. What to do? You can use static variables, but what if your application is multithreaded? There will be competition between threads for static variables. Solution-put the information at the input in ThreadLocal, at the output in the callback, you can pick it up.

The other scenario is the same cache. In a multithreaded program, it can be expensive to keep the cache thread-safe, because each access to the cache means expensive synchronization. Solution - start the software an instance of the cache in each thread, putting it in ThreadLocal.

A similar scenario is described here: multithreaded access to SimpleDateFormat is not allowed, and in order not to recreate the object every time it is called, you can cache it in ThreadLocal.

 7
Author: VladD, 2017-05-23 12:39:04

ThreadLocal is a type for a field that is bound to a thread. That is, each stream has its own field. Even if this field is static, each thread will still have its own field. Some believe that this is another "specific scope".

Read

 7
Author: KoVadim, 2017-02-27 19:10:43