Sobes.tech
Senior

What is Thread Context (ThreadLocal), what is it used for, and how does it work?

sobes.tech AI

Answer from AI

ThreadLocal is a mechanism in Java that allows storing data accessible only within a specific thread (Thread). Each thread has its own copy of the ThreadLocal variable, which eliminates the need for synchronization when accessing this data.

Why is ThreadLocal needed:

  • It allows storing thread-specific state, such as user sessions, transactional contexts, or date formatting objects.
  • It simplifies passing context between methods without explicitly passing parameters.

How it works:

  • When creating a ThreadLocal, a container for storing values is created.
  • Each thread, when accessing the ThreadLocal, gets its own separate copy of the value.
  • Inside the JVM, each thread has a map (map) ThreadLocal -> value.

Example of usage:

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

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

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

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

        t1.join();
        t2.join();
    }
}

In this example, each thread increments and outputs its own value without affecting the other thread.