How do you configure a custom thread pool for @Async tasks? @Async टास्क्स के लिए कस्टम थ्रेड पूल कैसे कॉन्फिगर करें?
Without a custom configuration, Spring's default async executor is SimpleAsyncTaskExecutor, which creates a brand-new thread for every task instead of reusing pooled threads — fine for very light usage but risky in production since it can exhaust system resources under load with no upper bound.
A custom ThreadPoolTaskExecutor bean lets you control core pool size, max pool size, queue capacity, and thread naming, giving predictable resource usage; multiple named executors can be defined and selected per method by passing the bean name to @Async("executorName") when different tasks have different concurrency needs.
@Bean(name = "emailExecutor")
public Executor emailExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("EmailAsync-");
executor.initialize();
return executor;
}
@Async("emailExecutor")
public void sendEmail(String to) { ... }बिना कस्टम कॉन्फिगरेशन के, स्प्रिंग का डिफ़ॉल्ट async एक्ज़ीक्यूटर SimpleAsyncTaskExecutor है, जो पूल्ड थ्रेड्स को दोबारा उपयोग करने के बजाय हर टास्क के लिए एक बिल्कुल नया थ्रेड बनाता है — यह लोड में सिस्टम संसाधनों को समाप्त कर सकता है।
एक कस्टम ThreadPoolTaskExecutor बीन आपको कोर पूल साइज़, मैक्स पूल साइज़, क्यू क्षमता को नियंत्रित करने देता है, जिससे अनुमानित संसाधन उपयोग मिलता है; अलग-अलग टास्क्स की अलग-अलग कंकरेंसी ज़रूरतों के लिए कई नामित एक्ज़ीक्यूटर्स डिफाइन किए जा सकते हैं।
@Bean(name = "emailExecutor")
public Executor emailExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.initialize();
return executor;
}Was this answer clear?