DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Spring and Threads: TaskExecutor

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.

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
Oct. 26, 17 · Java Zone · Tutorial
Like (27)
Save
Tweet
326.88K Views

Join the DZone community and get the full member experience.

Join For Free

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. 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.

Spring Framework

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Common Types Of Network Security Vulnerabilities In 2022
  • Python 101: Equality vs. Identity
  • Complete Guide to TestOps
  • How to Classify NSFW (Not Safe for Work) Imagery with AI Content Moderation using Java

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo