Reputation: 105
private void processEvents(List<Object> events) {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(
() -> processEventsAsynchronously(events));
while (!completableFuture.isDone() || completableFuture.isCancelled() || completableFuture.isCompletedExceptionally()) {
// waiting for all threads to get processed
}
if (completableFuture.isDone() || completableFuture.isCancelled() || completableFuture.isCompletedExceptionally()) {
executeRemainingFlow();
}
}
private void processEventsAsynchronously(List<Object> events) {
Executor executor = Executors.newFixedThreadPool(5);
for (Object event : events) {
Runnable runnable = () -> processEvent(event);
executor.execute(runnable);
}
}
private void processEvent(Object event) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void executeRemainingFlow() {
}
Here I want to process list of events asynchronously and once the processing is done I want to implement remaining flow. I tried to use CompletableFuture but the code inside the executer getting executed after executeRemainingFlow().
Upvotes: 1
Views: 1289
Reputation: 27115
Firs, get rid of the CompletableFuture.runAsync(...)
call. It serves no purpose (see my comments on your question, above.) Then, use Executors.awaitTermination()
to wait for all of the events to be processed. That leaves you with this:
private void processEvents(List<Object> events) {
Executor executor = Executors.newFixedThreadPool(5);
for (Object event : events) {
Runnable runnable = () -> processEvent(event);
executor.execute(runnable);
}
// Tell the `executor` to shut down _after_ all of the tasks have completed.
executor.shutdown();
// Wait until the executor has finished shutting down.
try {
executor.awaitTermination(9999, TimeUnit.DAYS);
}
catch (InterruptedException e) {
System.err.println("Uh Oh! **THIS** should never have happened:");
e.printStackTrace(System.err);
}
executeRemainingFlow();
}
Upvotes: 2