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

Mixing Sync and Async Methods with Custom Executors

Combining synchronous continuations (thenApply) with async ones (thenApplyAsync) and understanding executor usage.

Mixing Sync and Async Methods with Custom Executors

You'll learn how synchronous and asynchronous continuation methods interact when using custom executors, and how to control thread behavior strategically.

The Core Idea

When you chain CompletableFuture operations, you can freely mix synchronous methods (like thenApply, thenAccept) with asynchronous ones (like thenApplyAsync, thenAcceptAsync). The key insight: synchronous continuations may execute on whichever thread completes the previous stage, while async versions always submit to an executor.

With custom executors, this mixing becomes a powerful tool for resource management. You might use sync methods for lightweight transformations to avoid thread-switching overhead, then switch to async with a custom executor for expensive operations.

Strategic Thread Control

Consider this pattern:

ExecutorService customPool = Executors.newFixedThreadPool(4);

CompletableFuture.supplyAsync(() -> fetchData(), customPool)
    .thenApply(data -> quickTransform(data))  // Sync: runs on customPool thread
    .thenApplyAsync(data -> expensiveProcess(data), customPool)  // Async: submits to customPool
    .thenAccept(result -> System.out.println(result));  // Sync: might run on customPool thread

The thenApply runs immediately on whatever thread completed supplyAsync—avoiding unnecessary thread handoff. The thenApplyAsync explicitly submits work back to your custom pool, ensuring isolation. The final thenAccept piggybacks on the previous completion thread.

When to Mix

Use sync methods when operations are fast and thread identity doesn't matter. Use async methods with custom executors when you need guaranteed isolation, controlled parallelism, or want to prevent blocking a shared pool with long operations.

Key Takeaway: Mixing sync and async continuations with custom executors gives you fine-grained control over threading—optimize for performance by avoiding unnecessary thread switches while maintaining isolation for expensive operations by explicitly targeting your custom executor.