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.
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.
Have a look at the above DisplayTime class implementing the Runnable interface. Now its time to actually test our code using the TestTaskExecutor class.
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.