Spring and Threads: TaskExecutor
When you're working on long-running tasks for a web app, don't forget about Spring's TaskExecutor to help manage your components.
Join the DZone community and get the full member experience.
Join For FreeUsing threads in a web application is not unusual, especially when you have to develop long-running tasks.
Considering Spring, we must pay extra attention and use the tools it already provides, instead of spawning our own threads.
We want our threads to be managed by Spring and thus be able to use the other components of our application without any repercussions. We also want to shut down our application gracefully, without any work being in progress.
Spring provides the TaskExecutor as an abstraction for dealing with executors.
Spring’s TaskExecutor interface is identical to the java.util.concurrent.Executor interface.
There are a number of pre-built implementations of TaskExecutor included with the Spring distribution, and you can find more about them from the official documentation.
By providing your Spring environment with a TaskExecutor implementation, you will be able to inject the TaskExecutor to your beans and have access to managed threads.
package com.gkatzioura.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by gkatzioura on 4/26/17.
*/
@Service
public class AsynchronousService {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private TaskExecutor taskExecutor;
public void executeAsynchronously() {
taskExecutor.execute(new Runnable() {
@Override
public void run() {
//TODO add long running task
}
});
}
}
The first step is to add the TaskExecutor configuration to our Spring application.
package com.gkatzioura.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* Created by gkatzioura on 4/26/17.
*/
@Configuration
public class ThreadConfig {
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("default_task_executor_thread");
executor.initialize();
return executor;
}
}
Once we have our executor set up, the process is simple. We inject the executor to a Spring component and then we submit Runnable classes containing the tasks to be executed.
Since our asynchronous code might need to interact with other components of our application and have them injected, a nice approach is to create prototype scoped Runnable instances.
package com.gkatzioura;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* Created by gkatzioura on 10/18/17.
*/
@Component
@Scope("prototype")
public class MyThread implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(MyThread.class);
@Override
public void run() {
LOGGER.info("Called from thread");
}
}
Then, we are ready to inject the executor to our services and use it to execute runnable instances.
package com.gkatzioura.service;
import com.gkatzioura.MyThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by gkatzioura on 4/26/17.
*/
@Service
public class AsynchronousService {
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private ApplicationContext applicationContext;
public void executeAsynchronously() {
MyThread myThread = applicationContext.getBean(MyThread.class);
taskExecutor.execute(myThread);
}
}
In the next article, we will bring our multi-threaded codebase to a new level by using Spring’s asynchronous functions.
You can find the source code on GitHub.
Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments