Reputation: 443
The flow goes controller layer -> Service layer
Here I'm calling processLOBTransactions (Async method) method from the controller layer
How can I join all CompletableFuture responses in the controller layer? my requirement is after the execution of the processLOBTransactions for each list element from the controller, in the controller layer I wanna write logs kind of thing
Could anyone please give any suggestions on how to achieve this?
**Controller Layer:**
class ControllerLayer{
pktransaction.getLineOfBusinessTransaction().stream().forEach((lob) -> {
CompletableFuture<Boolean> futureResponse = flPbtService.processLOBTransactions(lob);
});
***//HERE How can i join all CompletableFuture Responses,and i wanna print logs like all thread completed***
}
**Service layer:**
class ServiceLayer{
@Async("threadPoolTaskExecutor")
public CompletableFuture<Boolean> processLOBTransactions(LineOfBusinessTransaction lobObj) {
// Doing some business logic and returning the CompletableFuture as Response
return CompletableFuture.completedFuture(new Boolean(true));
}
}
Upvotes: 1
Views: 1512
Reputation: 2360
CompletableFuture<Boolean> futureResponse
objects inside the forEach has to be stored in the Collection.parallelStream()
will not be used, ArrayList can be used to gather these referencesget()
obtain the result of exceptionget()
might wait until the actual task completes, so it may be better to use get(timeout, Unit)` to have a deterministic SLA contractsget
can throw exception and be sure handle appropriate actions by catching the exceptionget
with timeout, could not complete within timeout, then you can request cancel
if its not a high priority operation assuming the underlying task does not consume the interruption. (it a business logic) ArrayList<CompletableFuture<Boolean>> futures = new ArrayList<>();
IntStream.range(0, 10).forEach((lob) -> {
CompletableFuture<Boolean> futureResponse = CompletableFuture.completedFuture(new Boolean(true));
futures.add(futureResponse);
});
for (CompletableFuture<Boolean> future : futures) {
try {
System.out.println(future.get());
// or future.get(1, TimeUnit.SECONDS)
} catch (InterruptedException | ExecutionException e) {
System.out.println(e.getMessage());
//future.cancel(true); // if need to cancel the underlying task, assuming the task listens
}
}
Upvotes: 2