Course contentsShow
← Java
Lesson 2824 of 2,87051. CompletableFutureFree lesson

Performance Considerations: Sequential vs Parallel Composition

Understand when thenCompose's sequential execution is appropriate versus using thenCombine for independent parallel tasks.

Performance Considerations: Sequential vs Parallel Composition

You'll learn when to use thenCompose for sequential async operations versus thenCombine for independent parallel tasks, and the performance implications of each choice.

The Core Decision

When building async pipelines with CompletableFuture, you face a fundamental choice: should your operations run sequentially (one after the other) or in parallel (simultaneously)?

Sequential composition with thenCompose executes operations in order—the second stage waits for the first to complete before starting. This is necessary when the second operation depends on the first's result:

CompletableFuture<User> userFuture = fetchUserId()
    .thenCompose(id -> fetchUserProfile(id)); // Can't fetch profile without ID

Parallel composition (which you'll learn about with thenCombine) launches independent operations simultaneously and combines their results. Use this when tasks don't depend on each other:

// Both can run at the same time - neither needs the other's result
CompletableFuture<Weather> weatherFuture = fetchWeather();
CompletableFuture<News> newsFuture = fetchNews();

Performance Impact

Sequential composition is safer but slower—if each operation takes 100ms, you'll wait 200ms total. It's appropriate when:

  • Later stages need earlier results (dependency chain)
  • Operations must maintain order (writing then reading a file)

Parallel execution is faster but requires independence—two 100ms operations complete in ~100ms total. However, forcing parallel execution on dependent operations leads to errors or unnecessary blocking.

Think of it like cooking: You must chop vegetables before cooking them (sequential), but you can boil water while chopping vegetables (parallel).

Key Takeaway: Use thenCompose for dependent, sequential async operations where order matters; reserve parallel composition for truly independent tasks that can safely execute simultaneously to maximize performance.