Module java.base
Package java.lang

Class ScopeLocal<T>

java.lang.Object
java.lang.ScopeLocal<T>
Type Parameters:
T - the variable type

public final class ScopeLocal<T> extends Object
ScopeLocal is a preview API of the Java platform.
Programs can only use ScopeLocal when preview features are enabled.
Preview features may be removed in a future release, or upgraded to permanent features of the Java platform.
Represents a scoped variable.

A scope-local variable differs from a normal variable in that it is dynamically scoped and intended for cases where context needs to be passed from a caller to a transitive callee without using an explicit parameter. A scope-local variable does not have a default/initial value: it is bound, meaning it gets a value, when executing an operation specified to where(ScopeLocal, Object)PREVIEW. Code executed by the operation uses the get() method to get the value of the variable. The variable reverts to being unbound (or its previous value) when the operation completes.

Access to the value of a scoped variable is controlled by the accessibility of the ScopeLocal object. A ScopeLocal object will typically be declared in a private static field so that it can only be accessed by code in that class (or other classes within its nest).

ScopeLocal variables support nested bindings. If a scoped variable has a value then the runWithBinding or callWithBinding can be invoked to run another operation with a new value. Code executed by this methods "sees" the new value of the variable. The variable reverts to its previous value when the operation completes.

An inheritable scoped variable is created with the inheritableForType(Class)PREVIEW method and provides inheritance of values from parent thread to child thread that is arranged when the child thread is created. Unlike InheritableThreadLocal, inheritable scoped variable are not copied into the child thread, instead the child thread will access the same variable as the parent thread. The value of inheritable scoped variables should be immutable to avoid needing synchronization to coordinate access.

As an advanced feature, the snapshot() method is defined to obtain a ScopeLocal.Snapshot of the inheritable scoped variables that are currently bound. This can be used to support cases where inheritance needs to be done at times other than thread creation.

Unless otherwise specified, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

API Note:
The following example uses a scoped variable to make credentials available to callees.

   private static final ScopeLocal<Credentials> CREDENTIALS = ScopeLocal.forType(Credentials.class);

   Credentials creds = ...
   ScopeLocal.where(CREDENTIALS, creds).run(creds, () -> {
       :
       Connection connection = connectDatabase();
       :
   });

   Connection connectDatabase() {
       Credentials credentials = CREDENTIALS.get();
       :
   }
 
Since:
99
  • Method Details

    • hashCode

      public final int hashCode()
      Description copied from class: Object
      Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

      The general contract of hashCode is:

      • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
      • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
      • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
      Overrides:
      hashCode in class Object
      Returns:
      a hash code value for this object.
      See Also:
      Object.equals(java.lang.Object), System.identityHashCode(java.lang.Object)
    • where

      public static <T> ScopeLocal.Carrier where(ScopeLocalPREVIEW<T> key, T value)
      Creates a binding for a ScopeLocal instance. That ScopeLocal.Carrier may be used later to invoke a Callable or Runnable instance. More bindings may be added to the ScopeLocal.Carrier by the ScopeLocal.Carrier.where(ScopeLocal, Object)PREVIEW method.
      Type Parameters:
      T - the type of the ScopeLocal
      Parameters:
      key - the ScopeLocal to bind
      value - The value to bind it to
      Returns:
      A Carrier instance that contains one binding, that of key and value
    • where

      public static <T,​ U> U where(ScopeLocalPREVIEW<T> key, T value, Callable<U> op) throws Exception
      Creates a binding for a ScopeLocal instance and runs a value-returning operation with that bound ScopeLocal.
      Type Parameters:
      T - the type of the ScopeLocal
      U - the type of the Result
      Parameters:
      key - the ScopeLocal to bind
      value - The value to bind it to
      op - the operation to call
      Returns:
      the result
      Throws:
      Exception - if the operation completes with an exception
    • where

      public static <T> void where(ScopeLocalPREVIEW<T> key, T value, Runnable op)
      Creates a binding for a ScopeLocal instance and runs an operation with that bound ScopeLocal.
      Type Parameters:
      T - the type of the ScopeLocal
      Parameters:
      key - the ScopeLocal to bind
      value - The value to bind it to
      op - the operation to run
    • callWithSnapshot

      public static <R> R callWithSnapshot(Callable<R> op, ScopeLocal.Snapshot s) throws Exception
      Runs a value-returning operation with a snapshot of inheritable scoped variables.
      Type Parameters:
      R - the type of the result of the function
      Parameters:
      op - the operation to run
      s - the Snapshot. May be null.
      Returns:
      the result
      Throws:
      Exception - if the operation completes with an exception
    • runWithSnapshot

      public static void runWithSnapshot(Runnable op, ScopeLocal.Snapshot s)
      Runs an operation with this snapshot of inheritable scoped variables.
      Parameters:
      op - the operation to run
      s - the Snapshot. May be null.
    • forType

      public static <U,​ T extends U> ScopeLocalPREVIEW<T> forType(Class<U> type)
      Creates a scoped variable to hold a value with the given type.
      Type Parameters:
      T - the type of the scoped variable's value.
      U - a supertype of T. It should either be T itself or, if T is a parameterized type, its generic type.
      Parameters:
      type - The Class instance T.class
      Returns:
      a scope variable
    • inheritableForType

      public static <U,​ T extends U> ScopeLocalPREVIEW<T> inheritableForType(Class<U> type)
      Creates an inheritable scoped variable to hold a value with the given type.
      Type Parameters:
      T - the type of the scoped variable's value.
      U - a supertype of T. It should either be T itself or, if T is a parameterized type, its generic type.
      Parameters:
      type - The Class instance T.class
      Returns:
      a scope variable
    • get

      public T get()
      Returns the value of the variable.
      Returns:
      the value of the variable
      Throws:
      NoSuchElementException - if the variable is not bound (exception is TBD)
    • isBound

      public boolean isBound()
      Returns true if the variable is bound to a value.
      Returns:
      true if the variable is bound to a value, otherwise false
    • orElse

      public T orElse(T other)
      Return the value of the variable if bound, otherwise returns other.
      Parameters:
      other - the value to return if not bound, can be null
      Returns:
      the value of the variable if bound, otherwise other
    • orElseThrow

      public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
      Return the value of the variable if bound, otherwise throws an exception produced by the exception supplying function.
      Type Parameters:
      X - Type of the exception to be thrown
      Parameters:
      exceptionSupplier - the supplying function that produces an exception to be thrown
      Returns:
      the value of the variable if bound
      Throws:
      X - if the variable is unbound
    • snapshot

      public static ScopeLocal.Snapshot snapshot()
      Returns a "snapshot" of the inheritable scoped variables that are currently bound.

      This snapshot may be capured at any time. It is inteneded to be used in circumstances where values may be shared by sub-tasks.

      Returns:
      a "snapshot" of the currently-bound inheritable scoped variables. May be null.