Configure Executor service with spring boot application


In spring we can configure Executor service at once and use that thread pool whenever we want. Executor service is given by java to manage the threads. We can pass Callable objects to those threads and wait for results in the form of Future object.

Create Executor service in spring boot

package com.example.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;


@Service
public class UserService {

	@Bean("fixedThreadPool")
	public ExecutorService fixedThreadPool() {
		return Executors.newFixedThreadPool(5);
	}

	@Bean("singleThreaded")
	public ExecutorService singleThreadedExecutor() {
		return Executors.newSingleThreadExecutor();
	}

	@Bean("cachedThreadPool")
	public ExecutorService cachedThreadPool() {
		return Executors.newCachedThreadPool();
	}
	
	@Bean("worksteelThreadPool")
	public ExecutorService worksteelThreadPool() {
		return Executors.newWorkStealingPool();
	}
	
	@Bean("scheduledThreadPool")
	public ExecutorService scheduledThreadPool() {
		return Executors.newScheduledThreadPool(10);
	}
}

We can use these thread pools by using @Autowired annotation.

Service class uses Executor

package com.example.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;


@Service
public class EmpService {
	
    @Autowired
    @Qualifier("fixedThreadPool")
    private ExecutorService executorService;
    
    public <T> Future<T> execute(Callable<T> callable) {
        return executorService.submit(callable);
    }

}