Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

What are scoped values (ScopedValue, final in Java 25), and how do they differ from ThreadLocal?

A ScopedValue is a way to pass a value implicitly to all the code a method calls, without adding a parameter to every method. We bind it with ScopedValue.where(KEY, value).run(...) or .call(...), any code inside that call can read it with KEY.get(), and the binding is immutable and ends by itself when the call returns. A ThreadLocal, by contrast, is a mutable per-thread slot that lives until someone removes it and reaches child threads only through InheritableThreadLocal, by copying.

Why this question is asked

Every service has some context that almost every layer needs but nobody wants to pass by hand: the current user, a tenant, a request or transaction id. For years the answer was ThreadLocal, and it came with bugs: values leaking from one request into the next on pooled threads, memory that was never freed, and context that vanished when work moved to another thread. Scoped values became a final API in Java 25 to fix these problems, and interviewers ask about them to see whether we know why. In this answer, we will recap how ThreadLocal works, see the problems it causes, learn how scoped values are bound and read, look at how they pass to subtasks, and compare the two side by side.

1A Quick Recap of ThreadLocal

A ThreadLocal is a variable with one separate value per thread. Each thread that calls set() stores its own value, and get() returns the value of the current thread. Under the hood, every Thread object holds a small map from ThreadLocal objects to values.

Java
static final ThreadLocal<String> USER = new ThreadLocal<>();
USER.set("alice"); // stored in the current thread's map
service.handle(); // anywhere inside: USER.get() -> "alice"
USER.set("bob"); // any code can overwrite it
USER.remove(); // must be called, or the value stays on the thread

Notice three things about this design. The value is mutable, so any code along the way can change it, and we cannot tell where it was changed. It has no natural end: it stays until remove() is called. And it belongs to one thread, so a task we hand to another thread does not see it unless we use InheritableThreadLocal, which copies the parent's values into each child thread when the child is created.

2What Goes Wrong With ThreadLocal

On a thread pool, threads are reused for many requests. If a filter sets USER and an exception skips the remove() call, the next request on that thread starts with alice's identity. That is a security bug, and it comes from the fact that the lifetime of a ThreadLocal value is tied to the thread, not to the request.

Memory is the second problem. Values stay reachable from the thread until removed, so large objects cached in ThreadLocals live as long as the pool does. With virtual threads there can be a million threads, and a ThreadLocal per thread, plus InheritableThreadLocal copies for every child, adds up quickly. These are the problems scoped values were designed to remove.

3Binding and Reading a ScopedValue

A ScopedValue is created once, usually as a static final field. We never set it. Instead we bind a value for the duration of one call, and the binding is visible to all code that call runs, directly or indirectly, on the same thread.

Java
static final ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.where(USER, "alice").run(() -> service.handle());
// inside handle(), at any depth:
USER.get(); // "alice"
USER.isBound(); // true
// after run() returns:
USER.isBound(); // false
USER.get(); // throws NoSuchElementException
String result = ScopedValue.where(USER, "alice").call(() -> service.compute()); // call() returns a value
Step throughNested bindings of one ScopedValue
  1. outer call: where(USER, alice).run(...)USER.get() is alice
  2. nested call: where(USER, system).run(...)USER.get() is system, only inside
  3. back in the outer callUSER.get() is alice again
  4. after run() returnsUSER is unbound

4 layers, from the top down. Step through them one at a time.

A binding is like a local variable that called code can read: it lives exactly as long as the call.

The binding is immutable: there is no set() method, so code deeper in the call cannot change what the caller bound. It also ends automatically when run() or call() returns, whether normally or with an exception, so there is nothing to remove and nothing to forget. If inner code needs a different value for part of its work, it creates a nested binding with where(...).run(...) again. Inside that nested call the new value is visible, and when it returns, the outer value is back.

4Passing Context to Subtasks Cheaply

Scoped values were designed alongside structured concurrency. When a method opens a StructuredTaskScope (a preview API in Java 25) and forks subtasks, each subtask automatically sees the scoped values bound in the parent. Nothing is copied: the child threads read the same immutable bindings. This is safe because the scope guarantees the subtasks finish before the parent's call returns, so the bindings cannot end while a child still uses them.

Compare that with InheritableThreadLocal, which copies the map of values into every child thread at creation. With one virtual thread per subtask, that copying is real cost, and because the values are mutable, a child's change is invisible to the parent and other children, which is confusing. Notice also the limit: a thread started any other way, such as a task submitted to an ordinary executor, does not inherit the bindings. We must pass the value explicitly or rebind it there.

5Comparing the Two Side by Side

The difference comes down to lifetime and mutability. A ThreadLocal is storage owned by a thread; a ScopedValue is a parameter owned by a call. That makes scoped values the natural fit for request context such as user identity, tenant or trace and transaction ids passed through many layers. ThreadLocal is still the right tool when code really needs a mutable per-thread value, such as a reusable buffer on a platform thread pool, though with virtual threads such per-thread caches usually stop paying off.

ThreadLocal vs ScopedValue
QuestionThreadLocalScopedValue
How is a value set?set() at any timewhere(KEY, v).run(...) or call(...)
Can called code change it?Yes, set() againNo; a nested binding only
When does it end?When remove() is called, or the thread diesWhen the call returns
Child threadsOnly via InheritableThreadLocal, by copyingStructured scope subtasks, without copying
Typical useMutable per-thread stateRequest context through many layers

6Follow-up questions

What happens if I call get() on an unbound ScopedValue?

It throws NoSuchElementException. We can check first with isBound(), or use orElse(defaultValue) to get a fallback. A clean design binds the value once at the entry point, such as a web filter, so code below can rely on it being present and an unbound read reveals a real bug.

Are scoped values faster than ThreadLocal?

Reads are designed to be very cheap, comparable to a ThreadLocal read, and the JVM can cache them. The bigger gains are elsewhere: no copying into child threads, no cleanup, and no memory held after the call. For code with deep call stacks and many virtual threads, that matters more than the cost of a single read.

Since which version can I use them without a flag?

Scoped values were previewed from Java 21 and became final in Java 25 with JEP 506, so on Java 25 no --enable-preview is needed. The final API differs slightly from the previews, so code written against a preview may need small changes; check the Javadoc of your JDK.

7Conclusion

In this answer, we saw that a ThreadLocal is a mutable per-thread slot that lives until it is removed and reaches child threads only by copying through InheritableThreadLocal, which leads to leaks between requests and wasted memory. A ScopedValue is bound with ScopedValue.where(KEY, value).run(...) or .call(...), is read with KEY.get() only inside that call, cannot be changed except through a nested binding, and ends by itself when the call returns. It passes cheaply to structured concurrency subtasks and suits request context such as user identity and transaction ids.

What to say in the interviewAbout 80 seconds aloud

Open with

A ScopedValue is a way to pass a value implicitly down a call stack, final since Java 25. I create one as a static final field, then bind it for a call with ScopedValue.where, the key and the value, followed by run or call.

Then, if they want more

Any code inside that call, at any depth, can read it with get, and once the call returns the binding is gone. There is no set method, so code further down cannot change it; if it needs a different value for a while, it makes a nested binding, and the outer value comes back afterwards.

ThreadLocal is different in three ways. Its value is mutable, so anyone can overwrite it. It lives until someone calls remove, so on a pooled thread a missing remove leaks one request's data into the next, which is a classic security bug. And child threads only see it through InheritableThreadLocal, which copies all values into every new thread.

Scoped values are inherited by StructuredTaskScope subtasks without copying, which matters with many virtual threads. So I would use scoped values for request context like the authenticated user, tenant or a transaction id, and keep ThreadLocal for genuinely mutable per-thread state.

About this answer

Last updated
12 November 2026
Versions it names
Java 25, Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JEP 444, Virtual Threads
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What are scoped values (ScopedValue, final in Java 25), and how do they differ from...": https://scrivio-interview-library.netlify.app/java/virtual-threads/b69e6773be/