java / intermediate
Snippet
Custom Thread Pool Configuration with TaskExecutor
To control how asynchronous tasks are executed in a Spring application, you can define a custom TaskExecutor. This prevents the application from creating too many threads and allows you to tune performance based on system resources.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
@Configurationpublic class AsyncConfig {@Bean(name = "myExecutor")public Executor threadPoolTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.initialize();return executor;}}
spring
Breakdown
1
new ThreadPoolTaskExecutor()
Creates a managed thread pool provided by the Spring framework.
2
executor.setCorePoolSize(5)
Sets the base number of threads that remain alive even if they are idle.