Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

New Java Features Are Not Just for Interviews. Two Real-World Use Cases from Axelix

说明与用途

文章展示了用 ScopedValue 替代 ThreadLocal,以安全、自动地将身份验证上下文传递到深层传输层代码。ScopedValue 提供了受限的执行范围,防止令牌泄漏和被篡改。

问题

Passing an authentication token from an HTTP filter to deep transport-layer code without propagating it through many method parameters, while ensuring the token cannot be mutated or leaked between requests.

结果

ScopedValue replaced ThreadLocal for passing SecurityContext, eliminating mutable shared state, ensuring automatic cleanup, and preventing accidental token leakage or mutation.

工作流

  • 1. In the servlet filter, create a SecurityContext from the authenticated user.
  • 2. Call Master’s callWithinSecurityContext with the SecurityContext and a ThrowingCallable that performs the operation.
  • 3. Inside callWithinSecurityContext, use ScopedValue.where(...).call(...) to bind the SecurityContext for the duration of the callable.
  • 4. Within the callable, any code can retrieve the SecurityContext via ScopedValue.get() without passing it as a parameter.
  • 5. After the callable completes (normally or exceptionally), the ScopedValue binding is automatically removed, preventing leakage.

证据

In Java 25, ScopedValue was finalized. It solves a narrower problem than ThreadLocal: it allows a value to be passed down the call chain for the duration of a particular operation.

来源

The key difference lies in the model itself. A ThreadLocal resembles a mutable box attached to a thread. A ScopedValue describes the binding of a value within a dynamic execution scope.

来源

  • 记录日期: 2026-09-21T08:00:30.864Z