WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Core Java Β· Expert Β· question 74 of 100

What is a CompletableFuture allOf() method in Java? How is it used?

πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

The allOf method of CompletableFuture is a static method that allows you to wait for completion of all the provided futures. This method returns a new CompletableFuture that is completed when all of the provided futures have completed.

Here is an example of how to use the allOf method:

CompletableFuture<String> future1 = 
    CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = 
    CompletableFuture.supplyAsync(() -> "World");

CompletableFuture<Void> allFutures = 
    CompletableFuture.allOf(future1, future2);
allFutures.get(); // waits for all the futures to complete

System.out.println(future1.get() + " " + future2.get()); 
    // prints "Hello World"

In this example, we create two CompletableFuture objects, each of which returns a string. We then use the allOf method to create a new CompletableFuture that will complete when both of the original futures have completed. We then call the get method on the new CompletableFuture, which will block until both of the original futures have completed. Finally, we print the result of the two original futures concatenated together.

Note that the allOf method does not return the results of the individual futures. If you need to access the results of the individual futures, you will need to call the get method on each of them separately after the allOf method has completed.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview β€” then scores it.
πŸ“ž Practice Core Java β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

All 100 Core Java questions Β· All topics