[英]Execute multiple queries in parallel via Streams
我有以下方法:
public String getResult() {
List<String> serversList = getServerListFromDB();
List<String> appList = getAppListFromDB();
List<String> userList = getUserFromDB();
return getResult(serversList, appList, userList);
}
在這里,我按順序調用三個方法,然后點擊DB並獲取結果,然后我對從DB命中獲得的結果進行后處理。 我知道如何通過使用Threads
同時調用這三種方法。 但我想使用Java 8 Parallel Stream
來實現這一目標。 有人可以指導我如何通過Parallel Streams實現同樣的目標嗎?
編輯我只想通過Stream並行調用方法。
private void getInformation() {
method1();
method2();
method3();
method4();
method5();
}
您可以通過以下方式使用CompletableFuture
:
public String getResult() {
// Create Stream of tasks:
Stream<Supplier<List<String>>> tasks = Stream.of(
() -> getServerListFromDB(),
() -> getAppListFromDB(),
() -> getUserFromDB());
List<List<String>> lists = tasks
// Supply all the tasks for execution and collect CompletableFutures
.map(CompletableFuture::supplyAsync).collect(Collectors.toList())
// Join all the CompletableFutures to gather the results
.stream()
.map(CompletableFuture::join).collect(Collectors.toList());
// Use the results. They are guaranteed to be ordered in the same way as the tasks
return getResult(lists.get(0), lists.get(1), lists.get(2));
}
foreach
是用於side-effects
,你可以在parallel stream
上調用foreach
。 例如:
listOfTasks.parallelStream().foreach(list->{
submitToDb(list);
});
但是, parallelStream
使用常見的ForkJoinPool
,這可能對IO-bound
任務不利。
考慮使用CompletableFuture
並提供適當的ExecutorService
。 它提供了更大的靈活性( continuation
,配置)。 例如:
ExecutorService executorService = Executors.newCachedThreadPool();
List<CompletableFuture> allFutures = new ArrayList<>();
for(Query query:queries){
CompletableFuture<String> query = CompletableFuture.supplyAsync(() -> {
// submit query to db
return result;
}, executorService);
allFutures.add(query);
}
CompletableFuture<Void> all = CompletableFuture.allOf(allFutures.toArray(new CompletableFuture[allFutures.size()]));
如前所述,標准並行流可能不是最適合您的用例。 我將使用ExecutorService異步完成每個任務,並在調用getResult方法時“加入”它們:
ExecutorService es = Executors.newFixedThreadPool(3);
Future<List<String>> serversList = es.submit(() -> getServerListFromDB());
Future<List<String>> appList = es.submit(() -> getAppListFromDB());
Future<List<String>> userList = es.submit(() -> getUserFromDB());
return getResult(serversList.get(), appList.get(), userList.get());
不太清楚你的意思是什么,但如果你只是想在並行的這些列表上運行一些進程,你可以這樣做:
List<String> list1 = Arrays.asList("1", "234", "33");
List<String> list2 = Arrays.asList("a", "b", "cddd");
List<String> list3 = Arrays.asList("1331", "22", "33");
List<List<String>> listOfList = Arrays.asList(list1, list2, list3);
listOfList.parallelStream().forEach(list -> System.out.println(list.stream().max((o1, o2) -> Integer.compare(o1.length(), o2.length()))));
(它將打印每個列表中最冗長的元素)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.