Class Asynchronous.Result

java.lang.Object
jakarta.enterprise.concurrent.Asynchronous.Result
Enclosing class:
Asynchronous

public static final class Asynchronous.Result extends Object
Mechanism by which the Jakarta EE Product Provider makes available to the asynchronous method implementation the same CompletableFuture instance that the Jakarta EE Product Provider supplies to the caller of the asynchronous method.

Before invoking the asynchronous method implementation on a thread, the Jakarta EE Product Provider invokes the setFuture(java.util.concurrent.CompletableFuture<T>) method which makes available to the asynchronous method implementation the same CompletableFuture that the Jakarta EE Product Provider returns to the caller.

The asynchronous method implementation invokes the getFuture() method to obtain the same CompletableFuture that the Jakarta EE Product Provider returns to the caller. The asynchronous method implementation can choose to complete this future (normally or exceptionally) or otherwise arrange for its completion, for example upon completion of a pipeline of completion stages. Having this same CompletableFuture also enables the asynchronous method implementation to determine if the caller has forcibly completed (such as by cancellation or any other means) the CompletableFuture, in which case the asynchronous method implementation could decide to end immediately rather than continue processing.

For example,

 @Asynchronous
 public CompletableFuture<Double> hoursWorked(LocalDateTime from, LocalDateTime to) {
     CompletableFuture<Double> future = Asynchronous.Result.getFuture();
     if (future.isDone())
         return future;

     try (Connection con = ((DataSource) InitialContext.doLookup(
         "java:comp/env/jdbc/timesheetDB")).getConnection()) {
         ...
         for (ResultSet result = stmt.executeQuery(); result.next() && !future.isDone(); )
             ...
         future.complete(total);
     } catch (NamingException | SQLException x) {
         future.completeExceptionally(x);
     }
     return future;
 }
 
After the asynchronous method completes, the Jakarta EE Product Provider invokes the setFuture(java.util.concurrent.CompletableFuture<T>) method with a null value to clear it from the thread.
Since:
3.0