Junior — Middle
Can you explain what a ThreadLocal variable is in a multithreaded environment?
sobes.tech AI
Answer from AI
A ThreadLocal variable in Java provides storage for data that is unique to each thread. This means that each thread has its own copy of the variable, and changes in one thread do not affect the values in others.
This is useful when you need to preserve state or context specific to a thread, without the risk of conflicts between threads.
Example of usage:
ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
threadLocal.set(100); // Set value for the current thread
Integer value = threadLocal.get(); // Get value for the current thread
Thus, ThreadLocal helps avoid synchronization issues when working with threads.