Observability and reliability
Async diagnostic context
Restore context in reused worker threads. Executed synthetic Java 21 model, not framework integration.
Formal Syntax & Structure
java syntaxjava
scoped(captured,work)Working Example
Example Snippetjava
import java.util.concurrent.*;import java.util.function.Supplier;public class Main { static final ThreadLocal<String> CONTEXT=new ThreadLocal<>(); static <T> T scoped(String value, Supplier<T> work) { String before=CONTEXT.get(); CONTEXT.set(value); try { return work.get(); } finally { if(before==null) CONTEXT.remove(); else CONTEXT.set(before); } } public static void main(String[] args) { CONTEXT.set("request-A"); try(var pool=Executors.newSingleThreadExecutor()) { String captured=CONTEXT.get(); System.out.println(pool.submit(() -> scoped(captured, CONTEXT::get)).get(2,TimeUnit.SECONDS)); System.out.println(pool.submit(() -> String.valueOf(CONTEXT.get())).get(2,TimeUnit.SECONDS)); } catch (Exception e) { throw new IllegalStateException(e); } finally { CONTEXT.remove(); } }}