Home  >  Spring Core

Example of ThreadPoolTaskExecutor in Spring

By Arvind Rai, March 22, 2013
ThreadPoolTaskExecutor belongs to the package org.springframework.scheduling.concurrent. In spring to provide ThreadPoolExecutor directly to bean, it has provided ThreadPoolTaskExecutor. It works in jdk1.5. In spring we can directly inject ThreadPoolExecutor instance to our bean. To use ThreadPoolTaskExecutor in our bean, we need to implement interface AsyncConfigurer and then override getAsyncExecutor method. Let's see the example.
AppConfig.java
package com.concretepage;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AppConfig implements AsyncConfigurer{
	@Bean
	public AsyncTask asyncTask() {
	     return new AsyncTask();
	}
	@Override
	public Executor getAsyncExecutor() {
	    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(5);
            executor.setMaxPoolSize(10);
            executor.setQueueCapacity(10);
            executor.initialize();
            return executor;
	}
} 




AsyncTask.java
package com.concretepage;
import org.springframework.scheduling.annotation.Async;
public class AsyncTask {
	@Async
	public void doAsyncTask(){
		System.out.println("do some async task");
	}
}
 

AppTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 
		ctx.register(AppConfig.class);
		ctx.refresh();

		AsyncTask task= ctx.getBean(AsyncTask.class);
		task.doAsyncTask();
	}
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us