Thursday, September 18, 2025

ScopedValue in Java 20 to Use instead ThreadLocal

While ThreadLocal offers a convenient way to manage thread-specific data, developers must be aware of its potential pitfalls, particularly regarding memory management and debugging, and consider alternatives like ScopedValue in modern Java environments. Scoped values is a new API in Java 20 that enables developers to store and share immutable data within and across threads.

Scoped values in Java provide a mechanism for safely and efficiently sharing immutable data within a thread's call hierarchy and with child threads, without resorting to method parameters. They are designed as a modern alternative to ThreadLocal variables, particularly beneficial when working with virtual threads and structured concurrency.
Key characteristics of Scoped Values:
  • Immutable Data Sharing: 
    Scoped values hold immutable data, meaning the value associated with a ScopedValue instance cannot be changed after it's bound within a scope. This immutability simplifies reasoning about data flow and enhances thread safety.
  • Scoped Lifetime: 
    ScopedValue is bound to a value within a specific execution scope. The value is accessible only within that scope and its nested scopes (including child threads created using structured concurrency). Once the scope exits, the binding is automatically removed, preventing memory leaks and ensuring proper cleanup.
  • Efficient with Virtual Threads: 
    Unlike ThreadLocal variables, which can incur performance overhead due to map lookups and expensive inheritance mechanisms in scenarios with many virtual threads, ScopedValue is optimized for efficiency in such environments.
  • Implicit Parameter Passing: 
    They act as "implicit parameters," allowing data to be accessed by methods deep within a call stack without explicitly passing the data through each intermediate method. This reduces boilerplate code and improves readability.
  • One-Way Data Flow: 
    Scoped values primarily facilitate one-way data transmission from a caller to its callees. While a callee can rebind a ScopedValue for its own sub-scopes, it cannot modify the value seen by its caller.
  • Usage:
    • Declare a ScopedValueTypically as a private static final field.
    • Bind and Execute: Use ScopedValue.where(key, value).run(runnable) or ScopedValue.callWhere(key, value, callable) to bind a value to the ScopedValue and execute an operation within that scope.
    • Access Value: Within the scope, call scopedValue.get() to retrieve the bound value.

Example:
Java
import java.lang.ScopedValue;

public class ScopedValueExample {

private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();

public static void main(String[] args) {
ScopedValue.where(USER_ID, "user123").run(() -> {
System.out.println("Inside scope: " + USER_ID.get());
// Call other methods that can access USER_ID
performOperation();
});

// Outside the scope, USER_ID is not bound
System.out.println("Outside scope: " + (USER_ID.isBound() ? USER_ID.get() : "Not bound"));
}

private static void performOperation() {
System.out.println("In performOperation: " + USER_ID.get());
}
}
References from Google  AI review  and  https://www.baeldung.com/java-20-scoped-values

No comments:

Post a Comment

The AI Driven Software Developer, Optimize Innovate Transform

  The AI-Driven Software Developer: Optimize, Innovate, Transform": AI Transformation in Software Development : Understand how AI is re...