Top Description Methods
jakarta.enterprise.concurrent

public Interface ContextService

Imports
java.util.Map, java.util.concurrent.Callable, .CompletableFuture, .CompletionStage, .Executor, java.util.function.BiConsumer, .BiFunction, .Consumer, .Function, .Supplier

The ContextService provides methods for creating dynamic proxy objects (as defined by java.lang.reflect.Proxy). ContextService also creates proxy objects for functional interfaces (such as java.util.function.Function) that can be used as completion stage actions. Proxy objects run with the addition of context typically associated with applications executing in a Jakarta™ EE environment. Examples of such context are classloading, namespace, security, etc.

The proxy objects follow the same rules as defined for the java.lang.reflect.Proxy class with the following additions:

For example, to contextualize a single completion stage action such that it is able to access the namespace of the application component,

contextSvc = InitialContext.doLookup("java:comp/DefaultContextService");
stage2 = stage1.thenApply(contextSvc.contextualFunction(i -> {
    DataSource ds = InitialContext.doLookup("java:comp/env/dsRef");
    try (Connection con = ds.getConnection()) {
        PreparedStatement stmt = con.prepareStatement(sql);
        stmt.setInt(1, i);
        ResultSet result = stmt.executeQuery();
        return result.next() ? result.getInt(1) : 0;
    }
}));

Since
1.0

Method Summary

Modifier and TypeMethod and Description
public <
callable result type.
R
>
Callable<R>

Returns:

contextualized proxy instance that wraps execution of the call method with context.
contextualCallable
(Callable<R>
instance to contextualize.
callable
)

Wraps a java.util.concurrent.Callable with context that is captured from the thread that invokes contextualCallable.

public <
type of first parameter to consumer.
T
,
type of second parameter to consumer.
U
>
BiConsumer<T, U>

Returns:

contextualized proxy instance that wraps execution of the accept method with context.
contextualConsumer
(BiConsumer<T, U>
instance to contextualize.
consumer
)

Wraps a java.util.function.BiConsumer with context that is captured from the thread that invokes contextualConsumer.

public <
type of parameter to consumer.
T
>
Consumer<T>

Returns:

contextualized proxy instance that wraps execution of the accept method with context.
contextualConsumer
(Consumer<T>
instance to contextualize.
consumer
)

Wraps a java.util.function.Consumer with context that is captured from the thread that invokes contextualConsumer.

public <
type of first parameter to function.
T
,
type of second parameter to function.
U
,
function result type.
R
>
BiFunction<T, U, R>

Returns:

contextualized proxy instance that wraps execution of the apply method with context.
contextualFunction
(BiFunction<T, U, R>
instance to contextualize.
function
)

Wraps a java.util.function.BiFunction with context that is captured from the thread that invokes contextualFunction.

public <
type of parameter to function.
T
,
function result type.
R
>
Function<T, R>

Returns:

contextualized proxy instance that wraps execution of the apply method with context.
contextualFunction
(Function<T, R>
instance to contextualize.
function
)

Wraps a java.util.function.BiFunction with context that is captured from the thread that invokes contextualFunction.

public Runnable

Returns:

contextualized proxy instance that wraps execution of the run method with context.
contextualRunnable
(Runnable
instance to contextualize.
runnable
)

Wraps a java.lang.Runnable with context that is captured from the thread that invokes contextualRunnable.

public <
supplier result type.
R
>
Supplier<R>

Returns:

contextualized proxy instance that wraps execution of the supply method with context.
contextualSupplier
(Supplier<R>
instance to contextualize.
supplier
)

Wraps a java.util.function.Supplier with context captured from the thread that invokes contextualSupplier.

public <
the type of the instance to proxy
T
>
T

Returns:

a proxy for the input object that implements the specified interface.
createContextualProxy
(T
the instance of the object to proxy.
instance
,
Class<T>
the interface that the proxy should implement.
intf
)

Creates a new contextual object proxy for the input object instance.

public Object

Returns:

a proxy for the input object that implements all of the specified interfaces.
createContextualProxy
(Object
the instance of the object to proxy.
instance
,
Class<?>...
the interfaces that the proxy should implement.
interfaces
)

Creates a new contextual object proxy for the input object instance.

public <
the type of the interface
T
>
T

Returns:

a proxy for the input object that implements the specified interface.
createContextualProxy
(T
the instance of the object to proxy.
instance
,
Map<String, String>
the properties to use when creating and running the context object.
executionProperties
,
Class<T>
the interface that the proxy should implement.
intf
)

Creates a new contextual object proxy for the input object instance.

public Object

Returns:

a proxy for the input object that implements all of the specified interfaces.
createContextualProxy
(Object
the instance of the object to proxy.
instance
,
Map<String, String>
the properties to use when creating and running the context object.
executionProperties
,
Class<?>...
the interfaces that the proxy should implement.
interfaces
)

Creates a new contextual object proxy for the input object instance.

public Executor

Returns:

an executor that wraps the execute method with context.
currentContextExecutor
()

Captures thread context as an java.util.concurrent.Executor that runs tasks on the same thread from which executeis invoked but with context that is captured from the thread that invokes currentContextExecutor.

public Map<String, String>

Returns:

A copy of the current contextual object execution properties, or null if the contextualProxy is created without specifying any execution properties.
getExecutionProperties
(Object
the contextual proxy instance to retrieve the execution properties.
contextualProxy
)

Gets the current execution properties on the context proxy instance.

public <
completable future result type.
T
>
CompletableFuture<T>

Returns:

the new completable future.
withContextCapture
(CompletableFuture<T>
a completable future whose completion triggers completion of the new completable future that is created by this method.
stage
)

Returns a new java.util.concurrent.CompletableFuture that is completed by the completion of the specified stage.

public <
completion stage result type.
T
>
CompletionStage<T>

Returns:

the new completion stage.
withContextCapture
(CompletionStage<T>
a completion stage whose completion triggers completion of the new stage that is created by this method.
stage
)

Returns a new java.util.concurrent.CompletionStage that is completed by the completion of the specified stage.

Method Detail

contextualCallableback to summary
public <R> Callable<R> contextualCallable(Callable<R> callable)

Wraps a java.util.concurrent.Callable with context that is captured from the thread that invokes contextualCallable. Context is captured at the time contextualCallable is invoked.

When call is invoked on the proxy instance, context is first established on the thread that will run the call method, then the call method of the provided Callable is invoked. Finally, the previous context is restored on the thread, and the result of the Callable is returned to the invoker.

Parameters
<R>
callable result type.
callable:Callable<R>

instance to contextualize.

Returns:Callable<R>

contextualized proxy instance that wraps execution of the call method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized Callable is supplied to this method.
Since
3.0
contextualConsumerback to summary
public <T, U> BiConsumer<T, U> contextualConsumer(BiConsumer<T, U> consumer)

Wraps a java.util.function.BiConsumer with context that is captured from the thread that invokes contextualConsumer. Context is captured at the time contextualConsumer is invoked.

When accept is invoked on the proxy instance, context is first established on the thread that will run the accept method, then the accept method of the provided BiConsumer is invoked. Finally, the previous context is restored on the thread, and control is returned to the invoker.

Parameters
<T>
type of first parameter to consumer.
<U>
type of second parameter to consumer.
consumer:BiConsumer<T, U>

instance to contextualize.

Returns:BiConsumer<T, U>

contextualized proxy instance that wraps execution of the accept method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized BiConsumer is supplied to this method.
Since
3.0
contextualConsumerback to summary
public <T> Consumer<T> contextualConsumer(Consumer<T> consumer)

Wraps a java.util.function.Consumer with context that is captured from the thread that invokes contextualConsumer. Context is captured at the time contextualConsumer is invoked.

When accept is invoked on the proxy instance, context is first established on the thread that will run the accept method, then the accept method of the provided Consumer is invoked. Finally, the previous context is restored on the thread, and control is returned to the invoker.

Parameters
<T>
type of parameter to consumer.
consumer:Consumer<T>

instance to contextualize.

Returns:Consumer<T>

contextualized proxy instance that wraps execution of the accept method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized Consumer is supplied to this method.
Since
3.0
contextualFunctionback to summary
public <T, U, R> BiFunction<T, U, R> contextualFunction(BiFunction<T, U, R> function)

Wraps a java.util.function.BiFunction with context that is captured from the thread that invokes contextualFunction. Context is captured at the time contextualFunction is invoked.

When apply is invoked on the proxy instance, context is first established on the thread that will run the apply method, then the apply method of the provided BiFunction is invoked. Finally, the previous context is restored on the thread, and the result of the BiFunction is returned to the invoker.

Parameters
<T>
type of first parameter to function.
<U>
type of second parameter to function.
<R>
function result type.
function:BiFunction<T, U, R>

instance to contextualize.

Returns:BiFunction<T, U, R>

contextualized proxy instance that wraps execution of the apply method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized BiFunction is supplied to this method.
Since
3.0
contextualFunctionback to summary
public <T, R> Function<T, R> contextualFunction(Function<T, R> function)

Wraps a java.util.function.BiFunction with context that is captured from the thread that invokes contextualFunction. Context is captured at the time contextualFunction is invoked.

When apply is invoked on the proxy instance, context is first established on the thread that will run the apply method, then the apply method of the provided Function is invoked. Finally, the previous context is restored on the thread, and the result of the Function is returned to the invoker.

Parameters
<T>
type of parameter to function.
<R>
function result type.
function:Function<T, R>

instance to contextualize.

Returns:Function<T, R>

contextualized proxy instance that wraps execution of the apply method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized Function is supplied to this method.
Since
3.0
contextualRunnableback to summary
public Runnable contextualRunnable(Runnable runnable)

Wraps a java.lang.Runnable with context that is captured from the thread that invokes contextualRunnable. Context is captured at the time contextualRunnable is invoked.

When run is invoked on the proxy instance, context is first established on the thread that will run the run method, then the run method of the provided Runnable is invoked. Finally, the previous context is restored on the thread, and control is returned to the invoker.

Parameters
runnable:Runnable

instance to contextualize.

Returns:Runnable

contextualized proxy instance that wraps execution of the run method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized Runnable is supplied to this method.
Since
3.0
contextualSupplierback to summary
public <R> Supplier<R> contextualSupplier(Supplier<R> supplier)

Wraps a java.util.function.Supplier with context captured from the thread that invokes contextualSupplier. Context is captured at the time contextualSupplier is invoked.

When supply is invoked on the proxy instance, context is first established on the thread that will run the supply method, then the supply method of the provided Supplier is invoked. Finally, the previous context is restored on the thread, and the result of the Supplier is returned to the invoker.

Parameters
<R>
supplier result type.
supplier:Supplier<R>

instance to contextualize.

Returns:Supplier<R>

contextualized proxy instance that wraps execution of the supply method with context.

Exceptions
IllegalArgumentException:
if an already-contextualized Supplier is supplied to this method.
Since
3.0
createContextualProxyback to summary
public <T> T createContextualProxy(T instance, Class<T> intf)

Creates a new contextual object proxy for the input object instance.

Each method invocation will have the context of the application component instance that created the contextual object proxy.

The contextual object is useful when developing or using Java™ SE threading mechanisms propagating events to other component instances.

If the application component that created the proxy is not started or deployed, all methods on reflected interfaces may throw an java.lang.IllegalStateException.

For example, to execute a Runnable which is contextualized with the creator's context using a Java™ SE ExecutorService:

 public class MyRunnable implements Runnable {
     public void run() {
         System.out.println("MyRunnable.run with Jakarta EE Context available.");
     }
 }

 InitialContext ctx = new InitialContext();
 ThreadFactory threadFactory = (ThreadFactory) ctx
          .lookup("java:comp/env/concurrent/ThreadFactory");

 ContextService ctxService = (ContextService) ctx
          .lookup("java:comp/env/concurrent/ContextService");

 MyRunnable myRunnableInstance = ...;

 Runnable rProxy = ctxService.createContextualProxy(myRunnableInstance, Runnable.class);

 ExecutorService exSvc = Executors.newThreadPool(10, threadFactory);

 Future f = exSvc.submit(rProxy);

Parameters
<T>
the type of the instance to proxy
instance:T

the instance of the object to proxy.

intf:Class<T>

the interface that the proxy should implement.

Returns:T

a proxy for the input object that implements the specified interface.

Exceptions
IllegalArgumentException:
- if the intf argument is null or the instance does not implement the specified interface.
UnsupportedOperationException:
- if the intf interface is serializable but a thread context type does not support serialization.
createContextualProxyback to summary
public Object createContextualProxy(Object instance, Class<?>... interfaces)

Creates a new contextual object proxy for the input object instance.

This method is similar to <T> T createContextualProxy(T instance, Class<T> intf) except that this method can be used if the proxy has to support multiple interfaces.

Example:
 public class MyRunnableWork implements Runnable, SomeWorkInterface {
     public void run() {
         System.out.println("MyRunnableWork.run with Jakarta EE Context available.");
     }
     public void someWorkInterfaceMethod() {
         ...
     }
 }

 ThreadFactory threadFactory = ...;

 ContextService ctxService = ...;

 MyRunnableWork myRunnableWorkInstance = ...;

 Object proxy = ctxService.createContextualProxy(myRunnableWorkInstance,
                                  Runnable.class, SomeWorkInterface.class);

 // call SomeWorkInterface method on the proxy
 ((SomeWorkInterface) proxy).someWorkInterfaceMethod();

 ExecutorService exSvc = Executors.newThreadPool(10, threadFactory);

 // submit the proxy as a Runnable to the ExecutorService
 Future f = exSvc.submit( (Runnable)proxy);
Parameters
instance:Object

the instance of the object to proxy.

interfaces:Class<?>[]

the interfaces that the proxy should implement.

Returns:Object

a proxy for the input object that implements all of the specified interfaces.

Exceptions
IllegalArgumentException:
- if the interfaces argument is null or the instance does not implement all the specified interfaces.
UnsupportedOperationException:
- if any of the interfaces are serializable but a thread context type does not support serialization.
createContextualProxyback to summary
public <T> T createContextualProxy(T instance, Map<String, String> executionProperties, Class<T> intf)

Creates a new contextual object proxy for the input object instance.

The contextual object is useful when developing or using Java™ SE threading mechanisms propagating events to other component instances.

If the application component that created the proxy is not started or deployed, all methods on reflected interfaces may throw an java.lang.IllegalStateException.

This method accepts a Map object which allows the contextual object creator to define what contexts or behaviors to capture when creating the contextual object. The specified properties will remain with the contextual object.

For example, to call a Message Driven Bean (MDB) with the sender's context, but within the MDB's transaction:

 public class MyServlet ... {
     public void doPost() throws NamingException, JMSException {
        InitialContext ctx = new InitialContext();

        // Get the ContextService that only propagates
        // security context.
        ContextService ctxSvc = (ContextService)
            ctx.lookup("java:comp/env/SecurityContext");

        // Set any custom context data through execution properties
        Map<String, String> execProps = new HashMap<>();
        execProps.put("vendor_a.security.tokenexpiration", "15000");
        // Specify that contextual object should run inside the current
        // transaction.  If we have a failure, we don't want to consume
        // the message.
        execProps.put(ManagedTask.TRANSACTION, "USE_TRANSACTION_OF_EXECUTION_THREAD");

        ProcessMessage msgProcessor =
            ctxSvc.createContextualProxy(new MessageProcessor(), execProps,
            ProcessMessage.class);

        ConnectionFactory cf = (ConnectionFactory)
             ctx.lookup("java:comp/env/MyTopicConnectionFactory");
        Destination dest = (Destination) ctx.lookup("java:comp/env/MyTopic");
        Connection con = cf.createConnection();

        Session session = con.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(dest);

        Message msg = session.createObjectMessage((Serializable)msgProcessor);
        producer.send(dest, msg);
        ...

    }

  public class MyMDB ... {
    public void onMessage(Message msg) {
        // Get the ProcessMessage contextual object from the message.
        ObjectMessage omsg = (ObjectMessage)msg;
        ProcessMessage msgProcessor = (ProcessMessage)omsg.getObject();

        // Process the message in the specified context.
        msgProcessor.processMessage(msg);
    }
  }

  public interface  ProcessMessage {
      public void processMessage(Message msg);
  }

  public class MessageProcessor implements ProcessMessage, Serializable {
      public void processMessage(Message msg) {
          // Process the message with the application container
          // context that sent the message.

      }
  }
Parameters
<T>
the type of the interface
instance:T

the instance of the object to proxy.

executionProperties:Map<String, String>

the properties to use when creating and running the context object.

intf:Class<T>

the interface that the proxy should implement.

Returns:T

a proxy for the input object that implements the specified interface.

Exceptions
IllegalArgumentException:
- if the intf argument null or the instance does not implement the specified interface.
UnsupportedOperationException:
- if the intf interface is serializable but a thread context type does not support serialization.
createContextualProxyback to summary
public Object createContextualProxy(Object instance, Map<String, String> executionProperties, Class<?>... interfaces)

Creates a new contextual object proxy for the input object instance.

This method is similar to <T> T createContextualProxy(T instance, Map<String, String> executionProperties, Class<T> intf) except that this method can be used if the proxy has to support multiple interfaces.

Parameters
instance:Object

the instance of the object to proxy.

executionProperties:Map<String, String>

the properties to use when creating and running the context object.

interfaces:Class<?>[]

the interfaces that the proxy should implement.

Returns:Object

a proxy for the input object that implements all of the specified interfaces.

Exceptions
IllegalArgumentException:
- if the interfaces argument is null or the instance does not implement all the specified interfaces.
UnsupportedOperationException:
- if any of the interfaces are serializable but a thread context type does not support serialization.
currentContextExecutorback to summary
public Executor currentContextExecutor()

Captures thread context as an java.util.concurrent.Executor that runs tasks on the same thread from which executeis invoked but with context that is captured from the thread that invokes currentContextExecutor.

Example usage:

Executor contextSnapshot = contextSvc.currentContextExecutor();
...
// from another thread, or after thread context has changed,
contextSnapshot.execute(() -> obj.doSomethingThatNeedsContext());
contextSnapshot.execute(() -> doSomethingElseThatNeedsContext(x, y));

The returned Executor must raise IllegalArgumentException if an already-contextualized Runnable is supplied to its execute method.

Returns:Executor

an executor that wraps the execute method with context.

Since
3.0
getExecutionPropertiesback to summary
public Map<String, String> getExecutionProperties(Object contextualProxy)

Gets the current execution properties on the context proxy instance.

Parameters
contextualProxy:Object

the contextual proxy instance to retrieve the execution properties.

Returns:Map<String, String>

A copy of the current contextual object execution properties, or null if the contextualProxy is created without specifying any execution properties.

Exceptions
IllegalArgumentException:
thrown if the input contextualProxy is not a valid contextual object proxy created with the createContextualProxy method.
withContextCaptureback to summary
public <T> CompletableFuture<T> withContextCapture(CompletableFuture<T> stage)

Returns a new java.util.concurrent.CompletableFuture that is completed by the completion of the specified stage.

The new completable future gets its default asynchronous execution facility from this ContextService, using the same ManagedExecutorService if this ContextService was obtained by ManagedExecutorService#getContextService().

When dependent stages are created from the new completable future, and from the dependent stages of those stages, and so on, thread context is captured and/or cleared by the ContextService. This guarantees that the action performed by each stage always runs under the thread context of the code that creates the stage, unless the user explicitly overrides by supplying a pre-contextualized action.

Invocation of this method does not impact thread context propagation for the originally supplied completable future or any other dependent stages directly created from it (not using this method).

Parameters
<T>
completable future result type.
stage:CompletableFuture<T>

a completable future whose completion triggers completion of the new completable future that is created by this method.

Returns:CompletableFuture<T>

the new completable future.

Since
3.0
withContextCaptureback to summary
public <T> CompletionStage<T> withContextCapture(CompletionStage<T> stage)

Returns a new java.util.concurrent.CompletionStage that is completed by the completion of the specified stage.

The new completion stage gets its default asynchronous execution facility from this ContextService, using the same ManagedExecutorService if this ContextService was obtained by ManagedExecutorService#getContextService(), otherwise using the DefaultManagedExecutorService.

When dependent stages are created from the new completion stage, and from the dependent stages of those stages, and so on, thread context is captured and/or cleared by the ContextService. This guarantees that the action performed by each stage always runs under the thread context of the code that creates the stage, unless the user explicitly overrides by supplying a pre-contextualized action.

Invocation of this method does not impact thread context propagation for the originally supplied stage or any other dependent stages directly created from it (not using this method).

Parameters
<T>
completion stage result type.
stage:CompletionStage<T>

a completion stage whose completion triggers completion of the new stage that is created by this method.

Returns:CompletionStage<T>

the new completion stage.

Since
3.0