我想對從客戶端收到的每個請求并行運行幾個任務。我正在使用 spring boot 來運行服務器,并在 HTTP api 上呼叫它呼叫 getItems 方法。我正在使用 Executors.newCachedThreadPool() 來生成多個執行緒。我需要關于以下實作的一些輸入
- 對每個請求都使用 ExecutorService 執行緒池還是為應用程式創建一次池并重用它是否好?
- 如何決定 Executors 服務的池大小。
@Override
public List<Item> getItems(List<String> id) {
List<Item> items = new ArrayList<>();
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Callable<Item> > inventories = id.stream()
.map((itemId)-> (Callable<Item>) () -> {
List<InventoryNode> inventoryNodes = getInventory(itemId);
return getItem(inventoryNodes);
}).collect(Collectors.toList());
try {
List<Future<Item>> results = execSvc.invokeAll(inventories);
for(Future<Item> inventory :results){
if(inventory.isDone()){
items.add(inventory.get());
}
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}finally {
execSvc.shutdown();
}
return items;
}
uj5u.com熱心網友回復:
執行緒是通程序式代碼的獨立執行路徑。創建執行緒是一項昂貴的任務。有很多作業需要完成,比如分配記憶體、初始化執行緒堆疊。
最好為應用程式創建一次執行緒池,而不是為每個請求創建執行緒池。它減少了處理請求的開銷和延遲。在 Spring boot 中,您可以為此定義一個 bean。
@Bean("cachedThreadPool") public ExecutorService cachedThreadPool() { return Executors.newCachedThreadPool(); }考慮一個最大池大小為 50 的資料庫連接。在這種情況下,執行緒池為 100 是沒有意義的。因此,最好根據您所在的用例決定最大執行緒數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400896.html
