Enterprise Java

Spring and Threads: Async

Previously we started working with spring and the TaskExecutor, thus we became more familiar on how to use threads on a spring application.

However using the task executor might be cumbersome especially when we need to execute a simple action.

Spring’s Asynchronous methods come to the rescue.

Instead of messing with runnables and the TaskExecutor, you trade the control of the executor for the simplicity of the async functions.
In order to execute your function in another thread all you have to do is to annotate your functions with the @Async annotation.

Asynchronous methods come with two modes.

A fire and forget mode: a method which returns a void type.

@Async
    @Transactional
    public void printEmployees() {

        List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();
        employees.stream().forEach(e->System.out.println(e.getEmail()));
    }

A results retrieval mode: a method which returns a future type.

@Async
    @Transactional
    public CompletableFuture<List<Employee>> fetchEmployess() {
        List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();
        return CompletableFuture.completedFuture(employees);
    }

Pay extra attention to the fact that @Async annotations do not work if they are invoked by ‘this’. @Async behaves just like the @Transactional annotation. Therefore you need to have your async functions as public. You can find more information on the aop proxies documentation.

However using only the @Async annotation is not enough. We need to enable Spring’s asynchronous method execution capability by using the @EnableAsync annotation in one of our configuration classes.

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
@EnableAsync
public class ThreadConfig {

    @Bean
    public TaskExecutor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("sgfgd");
        executor.initialize();

        return executor;
    }

}

The next question is how we declare the resources and the threads pools that the async functions will use. We can get the answer from the documentation.

By default, Spring will be searching for an associated thread pool definition: either a unique TaskExecutor bean in the context, or an Executor bean named “taskExecutor” otherwise. If neither of the two is resolvable, a SimpleAsyncTaskExecutor will be used to process async method invocations.

However in some cases we don’t want the same thread pool to run all of application’s tasks. We might want separate threads pools with different configurations backing our functions.

To achieve so we pass to the @Async annotation the name of the executor we might want to use for each function.

For example  an executor with the name ‘specificTaskExecutor’ is configured.

@Configuration
@EnableAsync
public class ThreadConfig {

    @Bean(name = "specificTaskExecutor")
    public TaskExecutor specificTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.initialize();
        return executor;
    }

}

Then our function should set the qualifier value to determine the target executor of a specific Executor or TaskExecutor.

@Async("specificTaskExecutor")
public void runFromAnotherThreadPool() {
    System.out.println("You function code here");
}

The next article we will talk about transactions on threads.

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: Async

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