What is thread confinement (and stack confinement)? — Cracked Java
// Concurrency & Multithreading · Thread-Safety Patterns
MidTheory

What is thread confinement (and stack confinement)?

Thread confinement means restricting mutable data so it's only ever accessed from a single thread. If state is never shared, there's no race — confinement is the simplest thread-safety strategy, because it sidesteps synchronization entirely.

The three flavors

Ad-hoc confinement is confinement by convention only — you simply ensure (by discipline, not by the compiler) that an object is touched from one thread. It's fragile and the weakest form.

Stack confinement keeps an object reachable only through local variables. A local primitive or a reference to an object that never escapes the method lives on that thread's stack and is unreachable by any other thread. This is the most common and most robust everyday form of confinement — it's enforced naturally by scope.

int sumPrices(List<Order> orders) {
    int total = 0;                 // stack-confined primitive
    List<Order> filtered = new ArrayList<>(); // confined — never escapes
    for (Order o : orders) {
        if (o.isPaid()) filtered.add(o);
    }
    for (Order o : filtered) total += o.price();
    return total;                  // only the result leaves; the list does not
}

The ArrayList above is not thread-safe, but it doesn't need to be: it never escapes the method, so no other thread can reach it.

ThreadLocal confinement gives each thread its own private copy of a value via ThreadLocal<T>. It's the canonical fix for sharing a non-thread-safe object like SimpleDateFormat across requests: each thread gets its own formatter.

Watch the boundaries

Confinement only holds if the object truly never escapes. Returning a reference, storing it in a shared field, passing it to another thread's task, or capturing it in a Runnable submitted to a pool all break confinement instantly.

Mark your status