Quick revision
The short answer
First we put one accessor in front of the principal, so the 50 services stop touching the ThreadLocal and the storage can change underneath. Then the request entry point binds a ScopedValue and the accessor reads it, falling back to the ThreadLocal while services migrate. The limits are real: third-party integrations that read ThreadLocals directly still need them, a scoped value cannot be changed for the rest of the scope (code that switches principal mid-request must use a nested binding), and threads started outside a structured scope, such as plain executor tasks, do not see the value unless we pass it explicitly.
What to remember
In this answer, we planned the migration in phases: one accessor in front of the principal, a scoped value bound at every entry point with the ThreadLocal kept as a fallback, a counter to find code that still reads outside the binding, and removal only when every service is clean. We also covered the limitations: integrations that read ThreadLocals directly still need them, a scoped value cannot be reassigned so identity switches become nested bindings, and work on threads outside a structured scope needs the principal captured and rebound explicitly.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First we put one accessor in front of the principal, so the 50 services stop touching the ThreadLocal and the storage can change underneath. Then the request entry point binds a ScopedValue and the accessor reads it, falling back to the ThreadLocal while services migrate. The limits are real: third-party integrations that read ThreadLocals directly still need them, a scoped value cannot be changed for the rest of the scope (code that switches principal mid-request must use a nested binding), and threads started outside a structured scope, such as plain executor tasks, do not see the value unless we pass it explicitly.
Why this question is asked
Moving request context from ThreadLocal to ScopedValue sounds like a search and replace, but in a shared library used by 50 services it is a migration with many owners, unknown readers and behaviour that differs in subtle ways. Interviewers ask this to see whether we can plan a change that cannot happen in one deploy, and whether we know exactly where scoped values behave differently from ThreadLocals. In this answer, we will recap the two models, design the accessor that makes the change possible, walk through the migration phases, and then go through the limitations one by one with the workaround for each.
1A Quick Recap: Storage Versus Binding
Today the library probably looks like this: a filter calls SecurityHolder.set(principal) at the start of the request, code everywhere calls SecurityHolder.get(), and a finally block calls remove(). A ThreadLocal is a mutable slot per thread, so any code can set it at any time, and it lives until removed.
A ScopedValue, final in Java 25, works differently. We bind it for the duration of a call with ScopedValue.where(PRINCIPAL, p).run(...), any code inside that call reads it with PRINCIPAL.get(), and it ends when the call returns. It cannot be set. That difference in lifetime and mutability is the whole migration: every place that sets the principal, and every place that reads it from another thread, has to be looked at.
2Step One: One Accessor for Every Read
Before changing storage, we change how the services read the principal. The library exposes a single class, and the ThreadLocal becomes private.
Version one of the library ships the accessor while still using only the ThreadLocal underneath, and deprecates the old static field. Services move their reads to CurrentPrincipal.get() at their own pace, and a build check reports any remaining direct use. No behaviour has changed yet, so this phase is safe for 50 teams. The callAs method is the only way to set a principal in new code, and it already uses the binding model.
3Step Two: Bind at the Entry Point, Keep the Fallback
In the next library version, the request entry point binds the scoped value and also sets the ThreadLocal, so both old and new readers work. For a servlet application that is one filter; message listeners and scheduled jobs need the same wrapper at their entry points.
- v1: add CurrentPrincipal accessorstorage unchanged, direct field deprecated
- Services move reads to the accessorbuild check flags direct use
- v2: bind ScopedValue at entry points
ThreadLocalstill set as fallback - Fallback counter at zero?per service
- Zero for this service?YesTurn the ThreadLocal off for itNoFix the threads that read outside the binding
- v3: remove the ThreadLocalafter all 50 services are clean
6 steps in order. Play them, or step through them one at a time.
We roll this out service by service behind a configuration flag and watch for one signal: calls to get() that hit the fallback while SCOPED is unbound. A counter on that path shows exactly which code still runs outside the binding, usually work on other threads. When a service's counter stays at zero, it can turn the ThreadLocal off. When all services are clean, a later major version of the library removes it.
4Limitation: Code That Reads ThreadLocals Directly
Some code will never call our accessor. Logging libraries keep their mapped diagnostic context (the per-request fields such as user=alice added to every log line) in ThreadLocals. Security frameworks such as Spring Security keep their own context in a holder that defaults to a ThreadLocal strategy. For those, we keep setting the ThreadLocal at the entry point, or populate their own holder from the scoped value, for as long as they need it. So the honest goal is that our code no longer depends on ThreadLocal, not that the process contains none.
5Limitation: The Principal Cannot Change for the Rest of the Scope
Some services change the principal mid-request: a batch endpoint switches to a system user to write an audit record, or an admin action runs as another user. With a ThreadLocal that is a set() call followed, hopefully, by a set() back. With a scoped value there is no set(); the code must wrap the work in a nested binding.
This is a real code change, but it is also a safety improvement, because the identity can no longer leak past the code that needed it. Code that sets the principal once and expects later, unrelated code to see the new value cannot be migrated mechanically; it has to be restructured so the later code runs inside the binding.
6Limitation: Threads Started Outside a Structured Scope
Bindings are visible to the thread that made the call and to subtasks forked in a StructuredTaskScope inside it. They are not visible to threads started any other way: tasks submitted to an ordinary executor, @Async methods, CompletableFuture.supplyAsync, or callbacks run by a client library on its own threads. Today those places may work by accident through InheritableThreadLocal, or through a task decorator that copies the ThreadLocal. After the migration, they must capture the principal and rebind it.
In Spring, a TaskDecorator on the executors that @Async uses is the natural single place for this. And StructuredTaskScope, which would inherit the binding automatically, is still a preview API in Java 25, so most services will rely on explicit capture for now.
7Follow-up questions
Why not just switch the storage in one library release?
Because we do not know every reader. Some code reads the principal on another thread, some sets it mid-request, and some third-party integration reads the ThreadLocal directly. A big-bang release would turn those into authentication failures in production across 50 services at once. The accessor and the fallback counter let us find them first.
Is the migration worth it at all?
The main gains are safety and fit with virtual threads: no principal leaking into the next request when remove() is skipped, no mutation from deep inside the call, and no copying into every child thread. If the services are not moving to virtual threads and the leak bugs have never happened, the accessor step alone is still worth it, and the rest can wait.
How do you test that the binding really ends?
A unit test calls callAs with a principal, asserts get() returns it inside, and asserts that after the call isBound() is false and get() throws. A second test runs two requests on the same thread in a row through the filter and asserts the second one cannot see the first one's principal, which is the exact bug ThreadLocal allowed.
8Conclusion
In this answer, we planned the migration in phases: one accessor in front of the principal, a scoped value bound at every entry point with the ThreadLocal kept as a fallback, a counter to find code that still reads outside the binding, and removal only when every service is clean. We also covered the limitations: integrations that read ThreadLocals directly still need them, a scoped value cannot be reassigned so identity switches become nested bindings, and work on threads outside a structured scope needs the principal captured and rebound explicitly.
Open with
I would do it in phases, because with 50 services I cannot know every reader up front. First, the library gets one accessor, CurrentPrincipal.get, and the ThreadLocal becomes private behind it.
Then, if they want more
Nothing changes in behaviour, services move their reads at their own pace, and a build check flags direct use. Second, the entry points, the servlet filter, message listeners, scheduled jobs, bind a ScopedValue with ScopedValue.where around the rest of the request, and still set the ThreadLocal as a fallback.
The accessor reads the scoped value when it is bound and the ThreadLocal otherwise, and I count every fallback read, which tells me exactly which code runs outside the binding. When a service shows zero fallbacks, it drops the ThreadLocal; a later major version removes it entirely. The limitations are important.
Frameworks that read ThreadLocals directly, like logging MDC or a security context holder, still need them, so we keep populating those. A scoped value cannot be changed mid-request, so code that switches to a system user must use a nested binding instead of a set.
And threads started outside a structured scope, like executor tasks, @Async or CompletableFuture, do not see the binding, so we capture the principal and rebind it, ideally in one TaskDecorator.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25
- 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 "Your shared security library stores the authenticated principal in a ThreadLocal used by...": https://scrivio-interview-library.netlify.app/java/virtual-threads/63e14e07e4/