CodexBloom - Programming Q&A Platform

Java 17 ClassCastException When Using CompletableFuture and Custom ExecutorService

👀 Views: 339 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
java completablefuture executorservice exception Java

I'm relatively new to this, so bear with me... Hey everyone, I'm running into an issue that's driving me crazy... After trying multiple solutions online, I still can't figure this out. I'm working with a `ClassCastException` in my Java 17 application when I try to use a custom `ExecutorService` with `CompletableFuture`. My setup involves two classes: `Task` that implements `Callable<String>` and a `TaskExecutor` that creates and manages the `ExecutorService`. Here's a simplified version of what I'm trying to achieve: ```java import java.util.concurrent.*; class Task implements Callable<String> { @Override public String call() throws Exception { return "Task Completed!"; } } class TaskExecutor { private final ExecutorService executorService; public TaskExecutor() { this.executorService = Executors.newFixedThreadPool(2); } public CompletableFuture<String> executeTask() { return CompletableFuture.supplyAsync(() -> { try { return executorService.submit(new Task()).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }); } public void shutdown() { executorService.shutdown(); } } ``` When I call `executeTask()` from my main method, I get the following behavior: ``` Exception in thread "main" java.lang.ClassCastException: class java.lang.String want to be cast to class java.util.concurrent.Future ``` This seems to indicate that the result of the `submit()` method is being mishandled. I've ensured that my `Task` class correctly implements `Callable<String>`, and I'm also aware that calling `get()` directly on the future returned by `submit()` will block until the task completes. For context, I'm invoking `executeTask()` like this: ```java public static void main(String[] args) { TaskExecutor executor = new TaskExecutor(); CompletableFuture<String> futureResult = executor.executeTask(); futureResult.thenAccept(result -> System.out.println(result)); executor.shutdown(); } ``` What am I missing here? Why is `CompletableFuture.supplyAsync` causing a `ClassCastException`? I've tried debugging, but it seems the scenario arises specifically when interfacing with the `ExecutorService` and the way I'm trying to get the result. Any advice would be greatly appreciated! This is part of a larger API I'm building. I've been using Java for about a year now. Cheers for any assistance! I'm working in a CentOS environment. I'd really appreciate any guidance on this. For reference, this is a production service.