[英]Java asynchronous method execution
我正面臨一個場景,我必須針對給定的參數列表(一個集合)重復調用服務方法(涉及查詢執行)。
List<?> getResuls(List<String> params) {
List<?> results = new ArrayList<>();
// For every value in param call myMethod
params.forEach( param ->
results.add(myMethod ( param )));
return results;
}
myMethod (String s) {
// has series of queries execution based on
// different conditions and returns an object
// Involves HQL
}
請忽略語法錯誤 。
調用次數越多,執行時間就越多。
有沒有辦法可以並行執行myMethod()調用並在所有方法調用完成后獲得結果?
我瀏覽了一些有關CompletableFuture的博客,但不確定它是否對我的情況有幫助。
任何建議都會更有幫助。
我不確定parallelStream是否是您在這里尋找的內容...您也可以執行以下操作:
ForkJoinPool forkJoinPool = new ForkJoinPool(processCount//2 maybe);
forkJoinPool.submit(() -> {
youList.parallelStream().forEach {
//add your results to another list?
results.add(myMethod ( param )));
};
}).join();
return results;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.