How to run a background task using Spring Framework ThreadPoolTaskExecutor

Sometimes we need to execute a task in background in our application
We can use the class ThreadPoolTaskExecutor of Spring Framework to do that

To do it work we just need declare this bean in spring.xml config file as below

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.thread.ThreadPoolTaskExecutor">
  <property name="corePoolSize" value="5000" />
  <property name="maxPoolSize" value="5000" />
  <property name="queueCapacity" value="5000" />
public class ReportJob {
  private ThreadPoolTaskExecutor taskExecutor;
  public void startReport() throws IOException{
    taskExecutor.execute(); <- your thread to be executed here

Main properties

maxPoolSize – The max number of threads in the pool

corePoolSize – The current size of thread pool

queueCapacity – If all threads are executing in corePoolSize and the size of corePoolSize is equal to maxPoolSize the task will be allocated in the queue until a thread to be free. If you exceed the queueCapacity the task will be ignored