0
0
Spring Bootframework~5 mins

Custom thread pool configuration in Spring Boot

Choose your learning style9 modes available
Introduction

Custom thread pools help control how many tasks run at the same time. This keeps your app fast and stable.

When you want to run many tasks in the background without slowing the app.
When you need to limit how many threads run to save memory and CPU.
When you want to customize how threads start, wait, or stop.
When you want to improve app performance by managing task execution better.
Syntax
Spring Boot
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class ThreadPoolConfig {

    @Bean(name = "customThreadPool")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); // minimum threads
        executor.setMaxPoolSize(10); // max threads
        executor.setQueueCapacity(25); // tasks waiting
        executor.setThreadNamePrefix("MyPool-");
        executor.initialize();
        return executor;
    }
}

Use @Configuration to tell Spring this is a setup class.

@Bean creates the thread pool object for Spring to use.

Examples
This sets a smaller pool with more waiting tasks allowed.
Spring Boot
executor.setCorePoolSize(3);
executor.setMaxPoolSize(6);
executor.setQueueCapacity(50);
Gives threads a name prefix to help identify them in logs.
Spring Boot
executor.setThreadNamePrefix("Worker-");
Threads above core size will stop after 60 seconds of inactivity.
Spring Boot
executor.setKeepAliveSeconds(60);
Sample Program

This Spring Boot app creates a custom thread pool with 2 to 4 threads. It runs 5 tasks that print their thread name and task number. You see how threads from the pool handle tasks concurrently.

Spring Boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

@SpringBootApplication
public class ThreadPoolApp {

    public static void main(String[] args) {
        var context = SpringApplication.run(ThreadPoolApp.class, args);
        TaskRunner runner = context.getBean(TaskRunner.class);
        runner.runTasks();
    }

    @Bean(name = "customThreadPool")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("CustomPool-");
        executor.initialize();
        return executor;
    }
}

@Component
class TaskRunner {

    @Autowired
    private Executor customThreadPool;

    public void runTasks() {
        for (int i = 1; i <= 5; i++) {
            int taskId = i;
            customThreadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is running task " + taskId);
                try {
                    Thread.sleep(500); // simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
    }
}
OutputSuccess
Important Notes

Core pool size is the number of threads always kept alive.

Max pool size is the max threads allowed when demand is high.

Queue capacity holds tasks waiting when all threads are busy.

Summary

Custom thread pools help manage background tasks efficiently.

Set core size, max size, and queue to control thread behavior.

Use thread name prefixes to make debugging easier.