Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a List<CompletableFuture> One After Another

So I have an interface SetupTask that has only a single method run() which returns a CompletableFuture. I have a List<SetupTask>. I want to run the first one and when that is complete run the second and when that is complete run the third and so on. Originally I tried CompletableFuture.allOf() but that would run them all in parallel.

like image 688
Caleb Bassham Avatar asked Oct 17 '25 17:10

Caleb Bassham


1 Answers

You could chain all these tasks one after another consistently calling .thenCompose. This method executes some function that returns a CompletableFuture when the given stage is complete. I used CompletableFuture<Void> just to demonstrate how it would look like.

CompletableFuture<Void> current = CompletableFuture.completedFuture(null);
for (SetupTask task : tasks) {
    current = current.thenCompose(v -> task.run());
}
like image 170
Kirill Simonov Avatar answered Oct 19 '25 07:10

Kirill Simonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!