CodexBloom - Programming Q&A Platform

Java 11 CompletableFuture not completing when using custom ExecutorService

👀 Views: 82 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
java concurrency completablefuture Java

I've been banging my head against this for hours. I'm working on a project and hit a roadblock. I'm working with an scenario with `CompletableFuture` in Java 11 where the future doesn't complete as expected when I use a custom `ExecutorService`. I've set up a simple asynchronous task that should return a value after a delay, but it seems to hang indefinitely. Here's the code snippet that illustrates the question: ```java import java.util.concurrent.*; public class CompletableFutureTest { public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Task completed"; }, executor); future.thenAccept(result -> System.out.println(result)); executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); } } ``` The expected output is "Task completed" after a 2 second delay, but instead, the program hangs indefinitely at the `executor.awaitTermination(...)` line. I've also tried using `shutdownNow()` instead of `shutdown()`, but it doesn't seem to resolve the scenario. I can confirm that the task is being submitted to the executor as intended, and there are no exceptions thrown during execution. Could it be that my `ExecutorService` configuration is causing the scenario? I also want to make sure that I'm following best practices for managing the lifecycle of the `ExecutorService`. Any insights on why the `CompletableFuture` is not completing would be greatly appreciated! I'm using Java 3.11 in this project. Any suggestions would be helpful.