Shutdown and Cleanup of Custom Executors
What You'll Learn
You'll learn why and how to properly shut down custom thread pools used with CompletableFuture to prevent resource leaks.
The Resource Leak Problem
When you create a custom ExecutorService for your CompletableFuture workflows, those threads don't magically disappear when your CompletableFutures complete. Unlike the default ForkJoinPool.commonPool() (which the JVM manages), custom executors are your responsibility to clean up.
Think of it like renting a car: just because you've finished your road trip doesn't mean the rental company takes the car back automatically. You must return it explicitly, or you'll keep getting charged.
Proper Shutdown Pattern
After your CompletableFuture workflows complete, you must explicitly shut down custom executors:
ExecutorService customPool = Executors.newFixedThreadPool(4);
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "Task result", customPool)
.thenApplyAsync(result -> result.toUpperCase(), customPool);
// Wait for completion
future.join();
// CRITICAL: Shut down the executor
customPool.shutdown();
customPool.awaitTermination(60, TimeUnit.SECONDS);
Why This Matters
Without shutdown:
- Threads remain alive indefinitely
- Your application may never terminate (threads prevent JVM exit)
- Memory and system resources leak
- In server applications, repeated executor creation causes resource exhaustion
Best Practice Pattern
Always pair custom executor creation with shutdown in a try-finally or try-with-resources pattern:
ExecutorService executor = Executors.newFixedThreadPool(4);
try {
// All your CompletableFuture work here
CompletableFuture.supplyAsync(() -> doWork(), executor).join();
} finally {
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
}
Key Takeaway: Custom executors used with CompletableFuture must be explicitly shut down using shutdown() and awaitTermination() to release threads and prevent resource leaks—treat them like any other resource requiring cleanup.