Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ThreadLocal: initialize, set, get, and remove per-thread values

One shared `ThreadLocal` instance keeps a separate value for each thread. Removing a value lets the next read initialize it again, but the mechanism does not copy objects.

Version: Java SE 21

Syntax

java.lang.ThreadLocal<T> (Java SE 21)

import java.util.function.Supplier;

// Method signatures:
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier)
public void set(T value)
public T get()
public void remove()

In Java SE 21, multiple threads can use the same java.lang.ThreadLocal<T> instance, but each has its own entry for that instance. In ThreadLocal.withInitial/set/get/remove, withInitial is the static factory; set, get, and remove are instance methods that operate only on the calling thread's entry.

ThreadLocal.withInitial(supplier) creates the instance without calling the supplier. When get() finds no entry for the current thread, it calls supplier.get(), stores the result, and returns it. set(value) stores or replaces the value without calling the supplier, so setting before the first read skips initialization. set(null) stores null; the entry is still present. Passing null as the supplier to withInitial throws NullPointerException.

remove() deletes the entry without initializing it immediately. The next get() on that thread calls the supplier again unless a set(...) intervenes. In a thread pool, a later task on the same worker can read a leftover value, and data can be retained longer than intended. If a task owns the entry, clean it up with remove() in finally on that same worker.

The entries are separate, not necessarily the objects. If the supplier returns the same mutable object to both threads, they still share it. ThreadLocal neither deep-copies the object nor synchronizes access to it.

Examples

public class Main {
    private static final ThreadLocal<String> LOCAL =
            ThreadLocal.withInitial(() -> "default");

    public static void main(String[] args) throws InterruptedException {
        LOCAL.set("main-value");
        try {
            Thread worker = new Thread(() -> {
                try {
                    System.out.println("worker first get: " + LOCAL.get());
                    LOCAL.set(null);
                    System.out.println("worker after set(null): " + LOCAL.get());
                    LOCAL.remove();
                    System.out.println("worker after remove: " + LOCAL.get());
                } finally {
                    LOCAL.remove();
                }
            });
            worker.start();
            worker.join();
            System.out.println("main after join: " + LOCAL.get());
        } finally {
            LOCAL.remove();
        }
    }
}

Result

worker first get: default
worker after set(null): null
worker after remove: default
main after join: main-value

The worker reads `default`, then `null` after `set(null)`, then `default` again after `remove()`. `join()` waits for the worker to finish before the main thread prints its unchanged `main-value`.

Related lessons

  • Java · Lesson 33 · Advanced · Version: 2

Sources