Home java Why is the ThreadLocal class in Java needed?

Why is the ThreadLocal class in Java needed?




Explain in general terms what it is and what it is eaten with, and after that – maybe a link suitable for an example 🙂

Answer 1, authority 100%

ThreadLocal is a type that has a different meaning in each thread.

Why might this be needed? If multiple scripts.

For example, you have an application that uses various libraries and frameworks, the call chain goes very deep, and somewhere it 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 pass this additional information through the call chain. 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 entrance to ThreadLocal , at the exit in the callback you can pick it up.

Another scenario is the same cache. In a multithreaded program, keeping the cache thread-safe can be expensive, as each call to the cache means expensive synchronization. The solution is to create an instance of the cache in each thread by putting it in ThreadLocal .

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

Answer 2, authority 100%

ThreadLocal is such a type for a field, 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. Some people think this is another “specific scope”.


Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions