Interface ManagedExecutorService

  • All Superinterfaces:
    Executor, ExecutorService
    All Known Subinterfaces:
    ManagedScheduledExecutorService

    public interface ManagedExecutorService
    extends ExecutorService
    A manageable version of a 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 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 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 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,

    • If the supplied action is already contextual, (for example, contextService.createContextualProxy(action, Runnable.class)), then the action runs with the already-captured context.
    • Otherwise, each type of thread context is either propagated from the thread that creates the completion stage or the context is marked to be cleared, according to the configuration of the ManagedExecutorService that is the default asynchronous execution facility for the new stage and its parent stage. In the case that a ManagedExecutorService is supplied as the executor argument to a *Async method, the supplied ManagedExecutorService is used to run the action, but not to determine the thread context propagation and clearing.

    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 IllegalArgumentException if supplied with an action that implements ManagedTask.

    Since:
    1.0
    • Method Detail

      • completedFuture

        <U> CompletableFuture<U> completedFuture​(U value)

        Returns a new 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.

        Type Parameters:
        U - result type of the completable future.
        Parameters:
        value - result with which the completable future is completed.
        Returns:
        the new completable future.
        Since:
        3.0
      • completedStage

        <U> CompletionStage<U> completedStage​(U value)

        Returns a new 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.

        Type Parameters:
        U - result type of the completion stage.
        Parameters:
        value - result with which the completion stage is completed.
        Returns:
        the new completion stage.
        Since:
        3.0
      • copy

        <T> CompletableFuture<T> copy​(CompletableFuture<T> stage)

        Returns a new 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.

        Type Parameters:
        T - completable future result type.
        Parameters:
        stage - a completable future whose completion triggers completion of the new completable future that is created by this method.
        Returns:
        the new completable future.
        Since:
        3.0
      • copy

        <T> CompletionStage<T> copy​(CompletionStage<T> stage)

        Returns a new 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.

        Type Parameters:
        T - completion stage result type.
        Parameters:
        stage - a completion stage whose completion triggers completion of the new stage that is created by this method.
        Returns:
        the new completion stage.
        Since:
        3.0
      • failedFuture

        <U> CompletableFuture<U> failedFuture​(Throwable ex)

        Returns a new 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.

        Type Parameters:
        U - result type of the completable future.
        Parameters:
        ex - exception or error with which the completable future is completed.
        Returns:
        the new completable future.
        Since:
        3.0
      • failedStage

        <U> CompletionStage<U> failedStage​(Throwable ex)

        Returns a new 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.

        Type Parameters:
        U - result type of the completion stage.
        Parameters:
        ex - exception or error with which the completion stage is completed.
        Returns:
        the new completion stage.
        Since:
        3.0
      • getContextService

        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 CompletionStage and CompletableFuture instances that it creates via the withContextCapture methods.
        Returns:
        a ContextService with the same propagation settings as this ManagedExecutorService.
        Since:
        3.0
      • newIncompleteFuture

        <U> CompletableFuture<U> newIncompleteFuture()

        Returns a new incomplete 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.

        Type Parameters:
        U - result type of the completable future.
        Returns:
        the new completable future.
        Since:
        3.0
      • runAsync

        CompletableFuture<Void> runAsync​(Runnable runnable)

        Returns a new 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 - the action to run before completing the returned completion stage.
        Returns:
        the new completable future.
        Since:
        3.0
      • supplyAsync

        <U> CompletableFuture<U> supplyAsync​(Supplier<U> supplier)

        Returns a new 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.

        Type Parameters:
        U - result type of the supplier and returned completable stage.
        Parameters:
        supplier - an action returning the value to be used to complete the returned completion stage.
        Returns:
        the new completable future.
        Since:
        3.0