CodexBloom - Programming Q&A Platform

scenarios when using CompletableFuture with Spring's @Async - Thread pool exhaustion and task not executing

πŸ‘€ Views: 39 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
spring async completablefuture java

I'm writing unit tests and Quick question that's been bugging me - I'm working with an scenario with Spring's `@Async` annotation when using `CompletableFuture`... I have a service method that returns a `CompletableFuture<String>`, but it seems that the tasks are not executing as expected. Instead, I'm getting a timeout behavior and the following message in my logs: `Task java.util.concurrent.CompletableFuture$AsyncSupply@xxxx has not completed yet`. Here’s a simplified version of my code: ```java @Service public class MyAsyncService { @Async public CompletableFuture<String> asyncMethod() { try { Thread.sleep(5000); // Simulating a long-running task } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return CompletableFuture.completedFuture("Task Completed"); } } ``` I'm using Spring Boot 2.5.4 and have configured my executor like this: ```java @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(25); executor.initialize(); return executor; } } ``` When I call the `asyncMethod()` in my controller like this: ```java @RestController public class MyController { @Autowired private MyAsyncService myAsyncService; @GetMapping("/startTask") public String startTask() { myAsyncService.asyncMethod(); return "Task started"; } } ``` The task does not seem to execute, and I suspect it might be related to the configuration of `ThreadPoolTaskExecutor`. I've looked into increasing the core and max pool sizes, but I'm not sure how it will affect overall application performance. Am I missing something in my configuration or how I invoke the async method? Any advice would be greatly appreciated! Has anyone else encountered this? I'd really appreciate any guidance on this.