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

Providing a Custom Executor to runAsync

Understand how to supply a custom Executor to runAsync for controlling execution context and thread behavior.

Providing a Custom Executor to runAsync

What you'll learn: How to supply your own Executor to runAsync to control which thread pool executes your asynchronous tasks.

The Need for Control

By default, runAsync uses the ForkJoinPool.commonPool() to execute your fire-and-forget tasks. But just like with supplyAsync, you often need more control—whether to isolate workloads, manage thread priority, limit concurrency, or separate I/O-bound from CPU-bound tasks.

The Two-Argument Form

CompletableFuture.runAsync() has an overloaded version that accepts an Executor:

CompletableFuture<Void> future = CompletableFuture.runAsync(
    () -> {
        System.out.println("Running on: " + 
            Thread.currentThread().getName());
    },
    myCustomExecutor  // Your ExecutorService here
);

The second parameter is your custom Executor (typically an ExecutorService created via factory methods like newFixedThreadPool or newCachedThreadPool).

Practical Example

ExecutorService ioPool = Executors.newFixedThreadPool(10);

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // Perform I/O operation like writing logs
    System.out.println("Logging on dedicated pool");
}, ioPool);

// Don't forget to shut down your custom executor when done
ioPool.shutdown();

Why This Matters

Using a custom executor with runAsync lets you:

  • Separate concerns: Keep background logging tasks isolated from critical business logic
  • Control resource allocation: Dedicate a specific number of threads to side-effect operations
  • Prevent starvation: Avoid blocking the common pool with long-running I/O tasks

Key Takeaway: Supplying a custom Executor to runAsync gives you full control over execution context, letting you optimize thread usage and isolate different workload types in your asynchronous pipeline.