Search code examples
javamultithreadingcompletable-future

CompletableFuture.allOf meaning


Do I understand it well, that when I use

CompletableFuture.allOf("array of CompletableFuture")
                 .runAsync(()-> { "piece of code" });

first I have to wait until the array of CF are all done , and than the Runnable "piece of code" is done?


Solution

  • The CompletableFuture.allOf static method allows to wait for completion of all of the Futures provided as a var-arg.

    For example

    CompletableFuture<String> future1  
      = CompletableFuture.supplyAsync(() -> "Hello");
    CompletableFuture<String> future2  
      = CompletableFuture.supplyAsync(() -> "Beautiful");
    CompletableFuture<String> future3  
      = CompletableFuture.supplyAsync(() -> "World");
    
    CompletableFuture<Void> combinedFuture 
      = CompletableFuture.allOf(future1, future2, future3);