我需要在我的Spring應用程序中創建一個全局ThreadPoolTaskExecutor,它將負責在我的應用程序中運行多線程任務。Java中的受控ThreadPoolExecutor彈簧
但是,對於每個請求,我想限制從該全局ThreadPool使用的線程數。我應該如何確保根據請求執行此限制?
例如,
我創建一個全局線程池,最大池大小爲50個線程。但我想限制每個請求的線程數量來說5個線程。但是這5個線程只能從配置文件中定義的全局線程池中可用的50個線程中分配。
創建任務執行程序的配置類。
@Configuration
public class ThreadPoolConfiguration {
@Value("${threadpool.corepoolsize}")
int corePoolSize;
@Value("${threadpool.maxpoolsize}")
int maxPoolSize;
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(corePoolSize);
pool.setMaxPoolSize(maxPoolSize);
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}
}
Controller類
@RestController
public class WebController {
@Autowired
ThreadPoolTaskExecutor threadPool;
@RequestMapping("/process")
public String process(){
String msg = "";
List<Future<String>> futureList = new ArrayList<>();
for(int threadNumber = 0; threadNumber < 5; threadNumber ++){
CallableWorker callableTask = new CallableWorker(String.valueOf(threadNumber));
Future<String> result = threadPool.submit(callableTask);
futureList.add(result);
}
for(Future<String> future: futureList){
try {
msg += future.get() + "#####";
} catch (Exception e){}
}
return msg;
}
}
免責聲明:這只是示例代碼,我從一個blog post了。
我該如何實現這樣的設計?我沒有看到任何可以創建的子線程池。我也不想爲每個請求實例化一個線程池,因爲這會是災難性的。
有什麼建議嗎?
當一個請求有6個任務但僅限於5個線程時,你想要什麼樣的行爲?在排隊完成第6個任務之前,請等到前5個任務之一完成? –
是的,完全一樣。但是,如果另一個請求帶有5個任務,請將其與全局線程池分開放置5個線程。 而且,這兩個請求被提交後,從全局池10個線程被佔用和1個任務仍處於等待(從第一個請求) – Amriteya