Class ScopedValueScope

java.lang.Object
build.codemodel.dependency.injection.ScopedValueScope
All Implemented Interfaces:
Scope

public class ScopedValueScope extends Object implements Scope
A Scope backed by a ScopedValue. Within a single run(Runnable) or call(ScopedValue.CallableOp) invocation, every resolution of a scoped binding returns the same cached instance. The per-scope instance cache is automatically discarded when the invocation completes — no manual cleanup required.

Example usage:

final var requestScope = new ScopedValueScope();
framework.bindScope(RequestScoped.class, requestScope);

requestScope.run(() -> {
    // every resolution of a @RequestScoped type returns the same instance here
    var service = context.create(MyService.class);
});

Compared to a ThreadLocal-backed scope, this scope:

  • works safely with virtual threads — no per-thread storage overhead
  • cleans up automatically when the scope block exits — no memory leaks
  • requires an explicit scope boundary via run(Runnable) or call(ScopedValue.CallableOp)
Since:
Apr-2026
Author:
reed.vonredwitz
See Also:
  • Constructor Details

    • ScopedValueScope

      public ScopedValueScope()
  • Method Details

    • run

      public void run(Runnable action)
      Enters the scope and executes action. Within action, every resolution of a binding registered under this scope returns the same cached instance. The cache is discarded when action completes.
      Parameters:
      action - the action to run within this scope
    • call

      public <T, X extends Throwable> T call(ScopedValue.CallableOp<T,X> action) throws X
      Enters the scope, executes action, and returns its result. Behaves identically to run(Runnable) but allows a value to be returned from the scope.
      Type Parameters:
      T - the return type
      X - the exception type that action may throw
      Parameters:
      action - the action to call within this scope
      Returns:
      the result produced by action
      Throws:
      X - if action throws
    • scope

      public Binding<?> scope(ValueBinding<?> binding)
      Description copied from interface: Scope
      Wraps the given unscoped ValueBinding in a scoped Binding. The returned binding may cache, share, or re-create instances according to the scope's strategy.

      The signature uses wildcards so that implementations may be expressed as lambdas. The framework guarantees that the returned Binding produces values that are assignment-compatible with the type represented by Binding.dependency().

      Specified by:
      scope in interface Scope
      Parameters:
      binding - the unscoped ValueBinding whose ValueBinding.value() creates a fresh instance on each call
      Returns:
      a scoped Binding implementing this scope's instance lifecycle