Senior
What is the purpose of the ThreadLocal class?
sobes.tech AI
Answer from AI
The ThreadLocal class in Java is used to store data that is unique to each thread of execution. This means that each thread has its own copy of the variable, and data does not intersect between threads.
This is useful when you need to avoid issues with concurrent access to shared resources without the need for synchronization, for example, for storing user context, database connections, or other thread-specific objects.
Example of using ThreadLocal:
public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
Runnable task = () -> {
int value = threadLocalValue.get();
value += 1;
threadLocalValue.set(value);
System.out.println(Thread.currentThread().getName() + ": " + threadLocalValue.get());
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
}
}
In this example, each thread works with its own copy of the variable, which prevents data races.