Skip to content

Latest commit

 

History

History
79 lines (66 loc) · 2.98 KB

File metadata and controls

79 lines (66 loc) · 2.98 KB

Builders for ManagedExecutor and ThreadContext

MicroProfile Concurrency provides a fluent builder API to programmatically obtain instances of ManagedExecutor and ThreadContext. Builder instances are obtained via static builder() methods on ManagedExecutor and ThreadContext.

Example ManagedExecutor Builder Usage

    public void init(ServletConfig config) {
        executor = ManagedExecutor.builder()
                                  .propagated(ThreadContext.APPLICATION)
                                  .cleared(ThreadContext.ALL_REMAINING)
                                  .maxAsync(5)
                                  .build();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res) {
       completionStage = executor.runAsync(task1)
                             .thenRunAsync(task2)
                             ...
    }

    public void destroy() {
        executor.shutdown();
    }

Applications are encouraged to cache and reuse ManagedExecutor instances. It is the responsibility of the application to shut down ManagedExecutor instances that are no longer needed, so as to allow the container to efficiently free up resources.

Example ThreadContext Builder Usage

    threadContext = ThreadContext.builder()
                        .propagated(ThreadContext.APPLICATION, ThreadContext.SECURITY)
                        .cleared(ThreadContext.ALL_REMAINING)
                        .build();

    ...

    Function<Long, Long> contextFn = threadContext.contextualFunction(x -> {
        ... operations that requires security & application context
        return result;
    });

    // By using java.util.concurrent.CompletableFuture.supplyAsync rather
    // than a managed executor, context propagation is unpredictable,
    // except for the contextFn action that we pre-contextualized using
    // MicroProfile Concurrency's ThreadContext above.
    stage = CompletableFuture.supplyAsync(supplier)
                             .thenApplyAsync(function1)
                             .thenApply(contextFn)
                             ...

Builder instances retain their configuration after the build method is invoked and can be reused. Subsequent changes to builder configuration apply to subsequent invocations of the build method but do not impact ManagedExecutors that have already been built.