Sobes.tech
Senior

What is ThreadLocal?

sobes.tech AI

Answer from AI

ThreadLocal in Java is a class that allows creating variables that are local to each thread. Each thread accessing a ThreadLocal is provided with its own separate copy of the variable, which is not accessible to other threads.

This is useful when you need to store state that is specific to a thread without the need for synchronization.

Example of usage:

public class ThreadLocalExample {
    private static ThreadLocal<Integer> threadLocalCounter = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) {
        Runnable task = () -> {
            int count = threadLocalCounter.get();
            count++;
            threadLocalCounter.set(count);
            System.out.println(Thread.currentThread().getName() + " count: " + threadLocalCounter.get());
        };

        Thread t1 = new Thread(task, "Thread-1");
        Thread t2 = new Thread(task, "Thread-2");

        t1.start();
        t2.start();
    }
}

In this example, each thread has its own counter that does not intersect with others.

What is ThreadLocal? — Java - sobes.tech