SoFunction
Updated on 2025-04-13

Spring Boot's complete example of using thread pools to create multithreads

In Spring Boot 2, you can use@AutowiredInject thread pool (ThreadPoolTaskExecutororExecutorService), thereby managing the creation and execution of threads. The following is used@AutowiredA complete example of how to inject thread pool.

1. Inject ThreadPoolTaskExecutor via @Autowired

Step 1: Configure the thread pool

createThreadPoolTaskExecutorof@BeanConfiguration:

import ;
import ;
import ;
import ;
@Configuration
public class ThreadPoolConfig {
    @Bean(name = "customTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        (5);  // Number of core threads        (10);  // Maximum number of threads        (25); // Task queue capacity        ("Async-Executor-"); // Thread name prefix        ();
        return executor;
    }
}

Step 2: Inject thread pool using @Autowired

existServicelayer, through@AutowiredinjectionThreadPoolTaskExecutorAnd perform tasks:

import org.;
import org.;
import ;
import ;
import ;
@Service
public class AsyncTaskService {
    private static final Logger logger = ();
      @Autowired
    @Qualifier("customTaskExecutor") // Specify the Bean name through @Qualifier    private ThreadPoolTaskExecutor customTaskExecutor;
    // Submit asynchronous tasks    public void runAsyncTask() {
        (() -> {
            ("Asynchronous task execution,Thread name:{}", ().getName());
            try {
                (2000); // Simulation of time-consuming tasks            } catch (InterruptedException e) {
                ();
            }
            ("Asynchronous task completion,Thread name:{}", ().getName());
        });
    }
    // Submit an asynchronous task with return value    public Future<String> runAsyncTaskWithResult() {
        return (() -> {
            ("Execute asynchronous tasks with return values,Thread name:{}", ().getName());
            (2000);
            return "Task Complete";
        });
    }
}

Step 3: Call in Controller

existControllerlayer, through@AutowiredCallAsyncTaskService

import ;
import ;
import ;
import ;
@RestController
@RequestMapping("/task")
public class AsyncTaskController {
    @Autowired
    private AsyncTaskService asyncTaskService;
    @GetMapping("/run")
    public String runTask() {
        ();
        return "Task Submitted";
    }
    @GetMapping("/runWithResult")
    public String runTaskWithResult() throws Exception {
        Future<String> result = ();
        return "Task Results:" + ();
    }
}

2. Inject ThreadPoolTaskScheduler via @Autowired (for timing tasks)

Step 1: Configure ThreadPoolTaskScheduler

import ;
import ;
import ;
@Configuration
public class TaskSchedulerConfig {
    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        (5);  // Thread pool size        ("Scheduled-Task-");
        ();
        return scheduler;
    }
}

Step 2: Use @Autowired Injection in Service

import org.;
import org.;
import ;
import ;
import ;
@Service
public class ScheduledTaskService {
    private static final Logger logger = ();
    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;
    public void scheduleTask() {
        ScheduledFuture<?> future = (() -> {
            ("Perform timing tasks,Thread name:{}", ().getName());
        }, 5000);
    }
}

Step 3: Call in Controller

import ;
import ;
import ;
@RestController
@RequestMapping("/schedule")
public class ScheduleTaskController {
    @Autowired
    private ScheduledTaskService scheduledTaskService;
    @GetMapping("/start")
    public String startScheduledTask() {
        ();
        return "Timed task started";
    }
}

3. Inject ExecutorService via @Autowired

If you prefer Java nativeExecutorService, can be used@BeanConfiguration:

Step 1: Define the ExecutorService thread pool

import ;
import ;
import ;
import ;
@Configuration
public class ExecutorServiceConfig {
    @Bean
    public ExecutorService fixedThreadPool() {
        return (5);
    }
}

Step 2: Inject ExecutorService in Service

import org.;
import org.;
import ;
import ;
@Service
public class ExecutorServiceTask {
    private static final Logger logger = ();
    @Autowired
    private ExecutorService executorService;
    public void executeTask() {
        (() -> {
            ("Perform tasks,Thread name:{}", ().getName());
        });
    }
}

Step 3: Call in Controller

import ;
import ;
import ;
@RestController
@RequestMapping("/executor")
public class ExecutorServiceController {
    @Autowired
    private ExecutorServiceTask executorServiceTask;
    @GetMapping("/run")
    public String runTask() {
        ();
        return "Task Submitted";
    }
}

Summarize

Way Applicable scenarios Configuration method
ThreadPoolTaskExecutor Normal asynchronous tasks (@Asyncorexecute) @Autowired private ThreadPoolTaskExecutor
ThreadPoolTaskScheduler Timing tasks @Autowired private ThreadPoolTaskScheduler
ExecutorService Native Java thread pool @Autowired private ExecutorService

Recommended method

  • useThreadPoolTaskExecutorCombined@AutowiredTo manage asynchronous tasks (recommended).
  • useThreadPoolTaskSchedulerPerform scheduled tasks.
  • Avoid direct useExecutorService, because it is not managed by Spring, it cannot dynamically adjust thread pool parameters.

This is OKTake advantage of Spring Boot thread pool management, improve system performance, reduce resource consumption, and make the code easier to maintain! 🚀

This is the end of this article about Spring Boot using thread pool to create multi-threaded content. For more related Spring Boot thread pool to create multi-threaded content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!