Interview Questions

Spring Task Executor

In this article lets discuss about how to use Task Executor in Spring.

TaskExecutor is a simple outer layered framework to use Java's Concurrency API, the ThreadPoolExecutor.

ThreadPoolExecutor is an API used to execute set of threads and manage them efficiently.

org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor is a Spring bean to use the Java ThreadPoolExecutor in a very simple way.

Let us see an example. First we need to create the ThreadPoolTaskExecutor bean in the Spring config file.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd" >
<bean id="TaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="15" />
</bean>
</beans>

In the above bean, We have specified the Core Thread pool size, Maximum Thread pool size and the Queue capacity.

These are the main parameters we actually set for the Thread Pool Executor. Next we need to create a Runnable class and then execute the same.

class DisplayTime implements Runnable
{
        public void run()
        {
                System.out.println(new Date());
        }
}

Have a look at the above DisplayTime class implementing the Runnable interface. Now its time to actually test our code using the TestTaskExecutor class.

package in.techdive.spring;

import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.task.TaskExecutor;

public class TestTaskExecutor {

        public TestTaskExecutor() {
        }

        public static void main(String[] args) {
                 ApplicationContext ctx =
                         new FileSystemXmlApplicationContext("src\\TaskExec.xml");
                 
                 System.out.println("Started...");
                 
                 TaskExecutor tE = (TaskExecutor)ctx.getBean("TaskExecutor");
                 tE.execute(new DisplayTime());
        }
}

In this way, we can use ThreadPoolExecutor API in Java using Spring framework which makes our work easier.