Bird
0
0

You want to run two independent tasks asynchronously and wait concurrently for both to finish before proceeding. Which approach using @Async and CompletableFuture is correct?

hard📝 Application Q15 of 15
Spring Boot - Async Processing

You want to run two independent tasks asynchronously and wait concurrently for both to finish before proceeding. Which approach using @Async and CompletableFuture is correct?

  @Async
  public CompletableFuture<String> taskOne() { ... }

  @Async
  public CompletableFuture<String> taskTwo() { ... }

  public void runTasks() throws Exception {
    CompletableFuture<String> future1 = taskOne();
    CompletableFuture<String> future2 = taskTwo();
    // What to do here?
  }
AJust call taskOne() and taskTwo() without waiting
BCall future1.get() and future2.get() sequentially to wait
CUse CompletableFuture.allOf(future1, future2).join() to wait both
DCall future1.complete() and future2.complete() manually
Step-by-Step Solution
Solution:
  1. Step 1: Understand waiting for multiple async tasks

    Calling get() sequentially works but is inefficient and blocks one after another.
  2. Step 2: Use CompletableFuture.allOf for parallel waiting

    CompletableFuture.allOf(future1, future2).join() waits for both tasks to complete concurrently.
  3. Final Answer:

    Use CompletableFuture.allOf(future1, future2).join() to wait both -> Option C
  4. Quick Check:

    Wait all async tasks with allOf().join() [OK]
Quick Trick: Use allOf().join() to wait multiple async tasks together [OK]
Common Mistakes:
  • Calling get() sequentially causing unnecessary blocking
  • Not waiting at all and proceeding too early
  • Trying to manually complete futures which is incorrect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes