Managed Executor Service

For asynchronous execution in CDI managed beans or by using Java SE concurrency utilities, Java EE includes container-managed versions of ExecutorService and ScheduledExecutorService functionality. These are used to execute asynchronous tasks in container-managed threads. Instances of ManagedExecutorService and ManagedScheduledExecutorService are injected into the application's code. These instances can be used to execute their own runnable logic; however, they shine when combined together with Java SE concurrency utilities such as completable futures. The following shows the creation of completable futures using container-managed threads:

import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

@Stateless
public class Calculator {

    @Resource
    ManagedExecutorService mes;

    public CompletableFuture<Double> calculateRandomPi(int maxDecimalPlaces) {
        return CompletableFuture.supplyAsync(() -> new Random().nextInt(maxDecimalPlaces) + 1, mes)
                .thenApply(this::calculatePi);
    }

    private double calculatePi(long decimalPlaces) {
        ...
    }
}

The calculator bean returns a value of type completable future of double that may still be calculated while the calling context resumes. The future can be asked whether the calculation has finished. It can also be combined into subsequent executions. No matter where new threads are required in an enterprise application, Java EE functionality should be used to manage them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.247.53