ThreadLocal Per-Thread State

Give each thread its own counter via ThreadLocal.withInitial so mutable per-thread state needs no locking; clear it before pooled threads get reused.

JavaResilience

Code

snippet
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class PerThreadSteps {

    // 每个线程首次 get() 时创建自己的计数器:无锁、线程间互不可见
    private static final ThreadLocal<int[]> STEPS =
            ThreadLocal.withInitial(() -> new int[1]);

    static void step(String threadName) {
        int[] counter = STEPS.get();
        counter[0]++;
        System.out.println(threadName + " step " + counter[0]);
    }

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Runnable task = () -> {
            for (int i = 0; i < 3; i++) step(Thread.currentThread().getName());
        };
        pool.submit(task);
        pool.submit(task);
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("main counter: " + STEPS.get()[0]);
        STEPS.remove(); // 线程池复用线程:退出前清掉引用防泄漏
    }
}

How it works

Structurally, expect the class PerThreadSteps and the function step and nothing else.

Repetition is confined to for (int i = 0; i < 3; i++) step(Thread.currentThread().getName()); — the rest of the file is straight-line.

Applying it

The main signature reads static void step(String threadName)

Running the file prints labeled results such as main counter: — each operation’s effect is visible in the output.

Running the file executes main, which drives step in order.

Statements that matter

ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 3; i++) step(Thread.currentThread().getName());
ThreadLocal.withInitial(() -> new int[1]);

Interactive Tools for This Topic

FAQ

What does ThreadLocal Per-Thread State print when run?
Execute the whole file; each printed line is prefixed with a label like `main counter:`.