Enterprise Java

Spring and Threads: TaskExecutor

Using 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, and shutdown our application gracefully without any work being in progress.

Spring provides the TaskExecutor as an abstraction for dealing with executors. The 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, you can find more about them from the official documentation. By providing to your spring environment 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
            }
        });
    }
}

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 setup 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 as well 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);
    }

}

On the next article we will bring our multit-hreaded codebase to a new level by using spring’s asynchronous functions.

You can find the sourcecode on github.

Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Spring and Threads: TaskExecutor

Opinions expressed by Java Code Geeks contributors are their own.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button