import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean(name = "fixedThreadPool") public ThreadPoolTaskExecutor fixedThreadPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(3); executor.setQueueCapacity(10); executor.initialize(); return executor; } }
A fixed thread pool with core and max size 3 can run 3 tasks concurrently. Additional tasks are placed in the queue (capacity 10 here) and wait until a thread is free.
The correct methods to set core and max pool sizes are setCorePoolSize(int) and setMaxPoolSize(int). They are called with parentheses and arguments.
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(4); executor.setQueueCapacity(2); executor.initialize(); // 7 tasks submitted simultaneously
When the queue is full (2 tasks) and all 4 threads (max pool size) are busy, additional tasks cannot be accepted and are rejected.
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(6); executor.setQueueCapacity(0); executor.initialize(); // Submit 6 tasks simultaneously // Then call executor.getActiveCount()
With queue capacity 0, tasks cannot wait in queue. The pool expands up to max size 6 to run all tasks immediately, so active count is 6.
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setKeepAliveSeconds(10); executor.setAllowCoreThreadTimeOut(true); executor.initialize();
Setting allowCoreThreadTimeOut(true) lets core threads terminate if idle longer than keepAliveSeconds, freeing resources when idle.
