Top Description Methods
jakarta.enterprise.concurrent

public Interface ManagedExecutorService

extends ExecutorService
Known Direct Subinterfaces
jakarta.enterprise.concurrent.ManagedScheduledExecutorService
Imports
java.util.concurrent.CompletableFuture, .CompletionStage, .ExecutorService, java.util.function.Supplier

A manageable version of a java.util.concurrent.ExecutorService.

A ManagedExecutorService extends the Java™ SE ExecutorService to provide methods for submitting tasks for execution in a Jakarta™ EE environment. Implementations of the ManagedExecutorService are provided by a Jakarta EE Product Provider. Application Component Providers use the Java Naming and Directory Interface™ (JNDI) to look-up instances of one or more ManagedExecutorService objects using resource environment references. ManagedExecutorService instances can also be injected into application components through the use of the Resource annotation.

The Jakarta Concurrency specification describes several behaviors that a ManagedExecutorService can implement. The Application Component Provider and Deployer identify these requirements and map the resource environment reference appropriately.

The most common uses for a ManagedExecutorService is to run short-duration asynchronous tasks such as for processing of asynchronous methods in Jakarta Enterprise Beans or for processing async tasks for Servlets that supports asynchronous processing.

Tasks are run in managed threads provided by the Jakarta EE Product Provider and are run within the application component context that submitted the task. All tasks run without an explicit transaction (they do not enlist in the application component's transaction). If a transaction is required, use a jakarta.transaction.UserTransaction instance. A UserTransaction instance is available in JNDI using the name: "java:comp/UserTransaction" or by requesting an injection of a jakarta.transaction.UserTransaction object using the Resource annotation.

Example:

 public run() {
   // Begin of task
   InitialContext ctx = new InitialContext();
   UserTransaction ut = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
   ut.begin();

   // Perform transactional business logic

   ut.commit();
 }
 
Tasks can optionally provide an ManagedTaskListener to receive notifications of lifecycle events, through the use of ManagedTask interface.

Example:

 public class MyRunnable implements Runnable, ManagedTask {
   ...
   public void run() {
     ...
   }

   public ManagedTaskListener getManagedTaskListener() {
     return myManagedTaskListener;
   }
   ...
 }

 MyRunnable task = ...;
 ManagedExecutorService executor = ...;

 executor.submit(task); // lifecycle events will be notified to myManagedTaskListener
 
Asynchronous tasks are typically submitted to the ManagedExecutorService using one of the submit methods, each of which return a java.util.concurrent.Future instance. The Future represents the result of the task and can also be used to check if the task is complete or wait for its completion.

If the task is canceled, the result for the task is a java.util.concurrent.CancellationException exception. If the task is unable to run due to a reason other than cancellation, the result is a AbortedException exception.

Example:

 /**
  * Retrieve all accounts from several account databases in parallel.
  * Resource Mappings:
  *  type:      jakarta.enterprise.concurrent.ManagedExecutorService
  *  jndi-name: concurrent/ThreadPool
  */
 public List<Account> getAccounts(long accountId) {
   try {
       javax.naming.InitialContext ctx = new InitialContext();
       ManagedExecutorService mes = (ManagedExecutorService)
           ctx.lookup("java:comp/env/concurrent/ThreadPool");

       // Create a set of tasks to perform the account retrieval.
       ArrayList<Callable<Account>> retrieverTasks = new ArrayList<Callable<Account>>();
       retrieverTasks.add(new EISAccountRetriever());
       retrieverTasks.add(new RDBAccountRetriever());

       // Submit the tasks to the thread pool and wait for them
       // to complete (successfully or otherwise).
       List<Future<Account>> taskResults= mes.invokeAll(retrieverTasks);

       // Retrieve the results from the resulting Future list.
       ArrayList<Account> results = new ArrayList<Account>();
       for(Future<Account> taskResult : taskResults) {
           try {
               results.add(taskResult.get());
           } catch (ExecutionException e) {
               Throwable cause = e.getCause();
               // Handle the AccountRetrieverError.
           }
       }

       return results;

   } catch (NamingException e) {
       // Throw exception for fatal error.
   } catch (InterruptedException e) {
       // Throw exception for shutdown or other interrupt condition.
   }
 }


 public class EISAccountRetriever implements Callable<Account> {
     public Account call() {
         // Connect to our eis system and retrieve the info for the account.
         //...
         return null;
   }
 }

 public class RDBAccountRetriever implements Callable<Account> {
     public Account call() {
         // Connect to our database and retrieve the info for the account.
         //...
   }
 }

 public class Account {
     // Some account data...
 }
 

ManagedExecutorService provides various methods which correspond to the static methods of java.util.concurrent.CompletableFuture and its constructor/newIncompleteFuture method, enabling you to create completion stages that are backed by the ManagedExecutorService as the default asynchronous execution facility, both for those stages as well as all dependent stages that are created from those, and so on. This allows you to create pipelines of completion stage actions that run with consistent and predictable thread context, regardless of which thread each dependent action ends up running on.

Example:

 ManagedExectorService executor = InitialContext.doLookup("java:comp/DefaultManagedExecutorService");
 ...
 CompletableFuture<Integer> future = executor
    .supplyAsync(supplier)
    .thenApply(function1)
    .thenApplyAsync(function2)
    ...
 
 

Context propagation to completion stages that are backed by a ManagedExecutorService must be done in a consistent and predictable manner, which is defined as follows,

Each type of thread context is applied (either as cleared or previously captured) to the thread that runs the action. The applied thread context is removed after the action completes, whether successfully or exceptionally, restoring the thread's prior context.

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

Completion stages that are backed by a ManagedExecutorService must raise java.lang.IllegalArgumentException if supplied with an action that implements ManagedTask.

Since
1.0

Method Summary

Modifier and TypeMethod and Description
public <
result type of the completable future.
U
>
CompletableFuture<U>

Returns:

the new completable future.
completedFuture
(U
result with which the completable future is completed.
value
)

Returns a new java.util.concurrent.CompletableFuture that is already completed with the specified value.

public <
result type of the completion stage.
U
>
CompletionStage<U>

Returns:

the new completion stage.
completedStage
(U
result with which the completion stage is completed.
value
)

Returns a new java.util.concurrent.CompletionStage that is already completed with the specified value.

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

Returns:

the new completable future.
copy
(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.
copy
(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.

public <
result type of the completable future.
U
>
CompletableFuture<U>

Returns:

the new completable future.
failedFuture
(Throwable
exception or error with which the completable future is completed.
ex
)

Returns a new java.util.concurrent.CompletableFuture that is already exceptionally completed with the specified Throwable.

public <
result type of the completion stage.
U
>
CompletionStage<U>

Returns:

the new completion stage.
failedStage
(Throwable
exception or error with which the completion stage is completed.
ex
)

Returns a new java.util.concurrent.CompletionStage that is already exceptionally completed with the specified Throwable.

public ContextService

Returns:

a ContextService with the same propagation settings as this ManagedExecutorService.
getContextService
()

Returns a ContextService which has the same propagation settings as this ManagedExecutorService and uses this ManagedExecutorService as the default asynchronous execution facility for java.util.concurrent.CompletionStage and java.util.concurrent.CompletableFuture instances that it creates via the withContextCapture methods.

public <
result type of the completable future.
U
>
CompletableFuture<U>

Returns:

the new completable future.
newIncompleteFuture
()

Returns a new incomplete java.util.concurrent.CompletableFuture.

public CompletableFuture<Void>

Returns:

the new completable future.
runAsync
(Runnable
the action to run before completing the returned completion stage.
runnable
)

Returns a new java.util.concurrent.CompletableFuture that is completed by a task running in this executor after it runs the given action.

public <
result type of the supplier and returned completable stage.
U
>
CompletableFuture<U>

Returns:

the new completable future.
supplyAsync
(Supplier<U>
an action returning the value to be used to complete the returned completion stage.
supplier
)

Returns a new java.util.concurrent.CompletableFuture that is completed by a task running in this executor after it runs the given action.

Inherited from java.util.concurrent.ExecutorService:
awaitTerminationcloseinvokeAllinvokeAllinvokeAnyinvokeAnyisShutdownisTerminatedshutdownshutdownNowsubmitsubmitsubmit

Method Detail

completedFutureback to summary
public <U> CompletableFuture<U> completedFuture(U value)

Returns a new java.util.concurrent.CompletableFuture that is already completed with the specified value.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
<U>
result type of the completable future.
value:U

result with which the completable future is completed.

Returns:CompletableFuture<U>

the new completable future.

Since
3.0
completedStageback to summary
public <U> CompletionStage<U> completedStage(U value)

Returns a new java.util.concurrent.CompletionStage that is already completed with the specified value.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
<U>
result type of the completion stage.
value:U

result with which the completion stage is completed.

Returns:CompletionStage<U>

the new completion stage.

Since
3.0
copyback to summary
public <T> CompletableFuture<T> copy(CompletableFuture<T> stage)

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

The new completable future is backed by the ManagedExecutorService upon which copy is invoked, which serves as the default asynchronous execution facility for the new stage and all dependent stages created from it, and so forth.

When dependent stages are created from the new completable future, thread context is captured and/or cleared by the ManagedExecutorService. 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 supplied completable future or any other dependent stages directly created from it.

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
copyback to summary
public <T> CompletionStage<T> copy(CompletionStage<T> stage)

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

The new completion stage is backed by the ManagedExecutorService upon which copy is invoked, which serves as the default asynchronous execution facility for the new stage and all dependent stages created from it, and so forth.

When dependent stages are created from the new completion stage, thread context is captured and/or cleared by the ManagedExecutorService. 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 supplied stage or any other dependent stages directly created from it.

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
failedFutureback to summary
public <U> CompletableFuture<U> failedFuture(Throwable ex)

Returns a new java.util.concurrent.CompletableFuture that is already exceptionally completed with the specified Throwable.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
<U>
result type of the completable future.
ex:Throwable

exception or error with which the completable future is completed.

Returns:CompletableFuture<U>

the new completable future.

Since
3.0
failedStageback to summary
public <U> CompletionStage<U> failedStage(Throwable ex)

Returns a new java.util.concurrent.CompletionStage that is already exceptionally completed with the specified Throwable.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
<U>
result type of the completion stage.
ex:Throwable

exception or error with which the completion stage is completed.

Returns:CompletionStage<U>

the new completion stage.

Since
3.0
getContextServiceback to summary
public ContextService getContextService()

Returns a ContextService which has the same propagation settings as this ManagedExecutorService and uses this ManagedExecutorService as the default asynchronous execution facility for java.util.concurrent.CompletionStage and java.util.concurrent.CompletableFuture instances that it creates via the withContextCapture methods.

Returns:ContextService

a ContextService with the same propagation settings as this ManagedExecutorService.

Since
3.0
newIncompleteFutureback to summary
public <U> CompletableFuture<U> newIncompleteFuture()

Returns a new incomplete java.util.concurrent.CompletableFuture.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
<U>
result type of the completable future.
Returns:CompletableFuture<U>

the new completable future.

Since
3.0
runAsyncback to summary
public CompletableFuture<Void> runAsync(Runnable runnable)

Returns a new java.util.concurrent.CompletableFuture that is completed by a task running in this executor after it runs the given action.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
runnable:Runnable

the action to run before completing the returned completion stage.

Returns:CompletableFuture<Void>

the new completable future.

Since
3.0
supplyAsyncback to summary
public <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

Returns a new java.util.concurrent.CompletableFuture that is completed by a task running in this executor after it runs the given action.

This executor is the default asynchronous execution facility for the new completion stage that is returned by this method and all dependent stages that are created from it, and all dependent stages that are created from those, as so forth.

Parameters
<U>
result type of the supplier and returned completable stage.
supplier:Supplier<U>

an action returning the value to be used to complete the returned completion stage.

Returns:CompletableFuture<U>

the new completable future.

Since
3.0