ThreadPoolTaskExecutor : on shutdown, threads not awaiting full completion

6 hours ago 1
ARTICLE AD BOX

The context

I have:

a very simple method to run asynchronously : @Async public void asyncMethod() { System.out.println("entering method..."); try { Thread.sleep(10000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("exiting method..."); } An Executor service declared in a @Configuration that uses @EnableAsync @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setThreadNamePrefix("myAsyncStuff-"); executor.initialize(); return executor; } } The asynchronous method is then activated from an endpoint of a @RestController [not sharing the content of the controller, as it hardly matters] Finally, I am calling the controller's endpoint from a JUnit test, integrated within a full application context with @SpringBootTest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, useMainMethod = SpringBootTest.UseMainMethod.ALWAYS) public class SomeIntegrationTest { @Autowired MockMvc mockMvc; @Autowired ThreadPoolTaskExecutor taskExecutor; @Test void someTest() throws Exception { final var body = """ {"someKey": "someValue"} """; mockMvc.perform(post("/api/myEndpoint") .accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(body)) .andExpect(status().isOk()); taskExecutor.setWaitForTasksToCompleteOnShutdown(true); // ensuring that the taskExecutor awaits completion taskExecutor.shutdown(); // call to shutdown final var asyncFinished = taskExecutor.getThreadPoolExecutor().awaitTermination(5, TimeUnit.MINUTES); // await doing nothing !!! Assertions.assertTrue(asyncFinished); } }

The issue

The simple @Async method - correctly integrated following the official documentation - is called, the pool is shut down but awaitTermination does nothing and the thread is interrupted before the method reaches the end.

The logs on console, for someTest shows only the result of the first println:

> entering method...

Why is the pool no waiting for task completion???

Read Entire Article