Skip to content
Advertisement

Run task asynchronously: ManagedExcecutorService vs Microprofile fault tolerance @Asynchronous

I want to run an asynchronous task in a JavaEE openliberty environment. Ideally the task has to run at startup, but I don’t want that it blocks the startup of the WAR module itself. Also, I don’t want that on failure it prevents the whole application from starting up. So I guess that the solution is to run the task asynchronously in another thread.

So, it seems, I have basically two choices

To use the JavaEE managed executor service, like

https://openliberty.io/docs/latest/reference/config/managedExecutorService.html

public void serviceA() {
    managedExecutor.submit(() -> {
        System.out.println("ServiceA running");
    });
}

or use microprofile fault tolerance @asynchronous annotation, like

https://openliberty.io/docs/22.0.0.2/async-programming-fault-tolerance.html

@Asynchronous
public CompletionStage<String> serviceA() {
        System.out.println("ServiceA running");
}

Which of the two is to be preferred in which use cases? What are the advantages of the first vs the second approach or vice versa?

Advertisement

Answer

You will soon have a third option as well. Jakarta EE 10 is introducing an @Asynchronous annotation in the Concurrency 3.0 specification, and Open Liberty already has a beta of it,

https://openliberty.io/blog/2022/02/17/concurrency-3.0-22003-beta.html

All of these options are equally valid and it’s really just a matter of your preference of programming models. The CompletionStage pattern (possible with both of the @Asynchronous annotations, will allow you to chain dependent stages that will automatically run upon completion of the task which can be a nice alternative to code needing to wait for it to complete if you have that requirement. Concurrency 3.0 has other support for completion stages as well. If you won’t benefit from the completion stages aspect it might be slightly more efficient to use the ManagedExecutorService.submit method.

It should also be noted there is an issue open in the MicroProfile Fault Tolerance github repo proposing to move @Asynchronous to the Concurrency specification. With its immanent addition to Jakarta Concurrency, it is possible that the annotation could end up being discontinued in a future release of Fault Tolerance. The Fault Tolerance specification group would ultimately need to make that decision, but the existence of issue hints that it’s being considered.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement