Java.Multithreding.What is a ThreadLocal variable?

🧵🔐 What is a ThreadLocal Variable?

A ThreadLocal is a special Java class that provides thread-local storage.

📌 Each thread that accesses a ThreadLocal variable gets its own independent copy of the variable.

So even though many threads use the same ThreadLocal instance, each thread interacts only with its own isolated value.


✅ Why Use It?

  • Avoid shared mutable state
  • Thread-safe without synchronization
  • Commonly used for:
    • User sessions in web apps
    • Date formatters (which are not thread-safe)
    • Per-thread context like trace IDs or DB connections

🔧 Example:

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

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

        new Thread(task, "Thread-A").start();
        new Thread(task, "Thread-B").start();
    }
}

✅ Output (sample):

Thread-A: 713
Thread-B: 154

Each thread gets its own copy of threadId.


🔁 Methods

MethodDescription
get()Gets the value for the current thread
set(value)Sets the value for the current thread
remove()Clears the value (useful to prevent memory leaks)
withInitial(Supplier)Sets an initial value lazily

❗ Memory Leak Warning (Especially in Thread Pools)

If you forget to call remove(), and your thread is reused (like in a thread pool), the value may leak across tasks.

threadLocal.remove(); // ✅ Do this after the task finishes

🧠 Summary

FeatureThreadLocal
Shared across threads?❌ No — each thread has its own value
Thread-safe?✅ Yes — by design
Used forContext storage per thread
Common risksMemory leaks in long-lived threads (e.g., pools)
This entry was posted in Без рубрики. Bookmark the permalink.