【发布时间】:2022-01-01 21:50:22
【问题描述】:
我想在从客户端收到的每个请求上并行运行几个任务。我正在使用 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;
}
【问题讨论】:
标签: java multithreading spring-boot threadpool