Java Context Options: ThreadLocal vs Scoped Values

𝗧𝗵𝗿𝗲𝗮𝗱𝗟𝗼𝗰𝗮𝗹 𝘃𝘀 𝗦𝗰𝗼𝗽𝗲𝗱 𝗩𝗮𝗹𝘂𝗲𝘀: 𝗰𝗼𝗻𝘁𝗲𝘅𝘁 𝗶𝗻 𝗝𝗮𝘃𝗮 (𝗟𝗼𝗼𝗺 𝗲𝗿𝗮) 🧵 𝗧𝗵𝗿𝗲𝗮𝗱𝗟𝗼𝗰𝗮𝗹 Pros ✅ Zero “param passing” (requestId / tenant / MDC) ✅ Works with legacy libraries and frameworks ✅ Compatible with virtual threads (context is bound to the logical thread) Cons ❌ Hidden dependency (methods read context “from the air”) ❌ Doesn’t reliably propagate across async/reactive boundaries ❌ On pooled platform threads: stale context + memory retention if you forget cleanup ❌ Bad fit for “per-thread caches” in a world of many short-lived virtual threads Use it when ✅ Request-scoped, mostly read-only context ✅ You must integrate with ThreadLocal/MDC-based tooling 🚫 Never store heavy objects / large graphs / caches Typical mistakes 🚫 Forgetting cleanup (remove()/reset) in long-lived threads / pools 🚫 Using it as a global service locator 🚫 Assuming it “just works” through CompletableFuture/reactive chains 𝗦𝗰𝗼𝗽𝗲𝗱 𝗩𝗮𝗹𝘂𝗲𝘀 What it is Context bound to a scope (execution block), not “stored on a thread” Automatic lifetime: when scope ends, the value is gone Pros ✅ Clear boundaries + automatic cleanup ✅ Better match for Loom + structured concurrency thinking ✅ Encourages immutable request context Cons ❌ Still evolving (preview in Java 21) ❌ Ecosystem/tooling support is not as universal as ThreadLocal/MDC yet Use it when ✅ New Loom-first code: requestId / tenant / trace context ✅ You want explicit lifetime and fewer “implicit state” bugs 𝗠𝘆 𝗼𝗽𝗶𝗻𝗶𝗼𝗻 * Default for new services: 𝗦𝗰𝗼𝗽𝗲𝗱 𝗩𝗮𝗹𝘂𝗲𝘀 for request context. * Keep ThreadLocal only as a compatibility layer (MDC/legacy libs) and treat it as “unsafe by default”. Rule of thumb * “Context for this execution tree” → Scoped Values * “Legacy integration needs it” → ThreadLocal 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: 𝗪𝗵𝗲𝗿𝗲 𝗱𝗼 𝘆𝗼𝘂 𝗸𝗲𝗲𝗽 𝗿𝗲𝗾𝘂𝗲𝘀𝘁 𝗰𝗼𝗻𝘁𝗲𝘅𝘁 𝘁𝗼𝗱𝗮𝘆 - 𝗠𝗗𝗖/𝗧𝗵𝗿𝗲𝗮𝗱𝗟𝗼𝗰𝗮𝗹 𝗼𝗿 𝗲𝘅𝗽𝗹𝗶𝗰𝗶𝘁 𝗽𝗮𝗿𝗮𝗺𝘀? 👇 #Java #Concurrency #VirtualThreads #ProjectLoom #Observability

  • No alternative text description for this image

Good diff, thank you! Wouldn't you like to show scoped values on some samples?

Like
Reply

To view or add a comment, sign in

Explore content categories