Java / Java 21 Interview Questions
What are Scoped Values in Java 21 and how do they differ from ThreadLocal?
Scoped Values (JEP 446, first preview in Java 21) provide an immutable, bounded alternative to ThreadLocal designed specifically for virtual threads. A ScopedValue holds a value for the duration of a bounded scope (a ScopedValue.where(...).run(...) block) and is automatically removed when the scope exits — no manual remove() required.
| Aspect | ThreadLocal | ScopedValue |
|---|---|---|
| Mutability | Mutable — set() anytime | Immutable — set once per scope, read-only inside |
| Lifetime | Lives until remove() or thread death | Lives only within the where().run() scope |
| Inheritance | Must opt-in (InheritableThreadLocal) | Inherited automatically by child scopes |
| Memory with VTs | Memory leak risk at millions of VTs | Bounded — cleaned up at scope exit |
| Thread safety | Per-thread copy, OK | Immutable, inherently safe |
// Declare a scoped value (typically static final)
private static final ScopedValue CURRENT_USER =
ScopedValue.newInstance();
// Bind and run — value is available inside the lambda
ScopedValue.where(CURRENT_USER, currentUser)
.run(() -> {
processRequest(); // can read CURRENT_USER anywhere in call tree
});
// Inside processRequest or any method it calls:
void processRequest() {
User user = CURRENT_USER.get(); // always present in this scope
// ... use user ...
}
// Nested rebinding — inner scope shadows outer
ScopedValue.where(CURRENT_USER, adminUser)
.run(() -> {
// CURRENT_USER is adminUser here
ScopedValue.where(CURRENT_USER, guestUser)
.run(() -> {
// CURRENT_USER is guestUser here
});
// CURRENT_USER is adminUser again
}); Scoped Values are particularly useful for passing context (request IDs, current user, database transaction) down through a call stack without threading it through every method parameter — the same use case as ThreadLocal, but safe and efficient at millions of virtual threads.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
