简体   繁体   English

Java异步方法执行

[英]Java asynchronous method execution

I am facing a scenario where I have to call a service method ( which involves queries execution ) repeatedly for the given list of paramers - a collection. 我正面临一个场景,我必须针对给定的参数列表(一个集合)重复调用服务方法(涉及查询执行)。

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
 }

Please ignore syntax errors . 请忽略语法错误

The more the number of call more is the execution time. 调用次数越多,执行时间就越多。

Is there way that I can execute myMethod () calls in parallel and obtain a result when all the method calls complete.? 有没有办法可以并行执行myMethod()调用并在所有方法调用完成后获得结果?

I skimmed through few blogs about CompletableFuture but not sure will it help my scenario. 我浏览了一些有关CompletableFuture的博客,但不确定它是否对我的情况有帮助。

Any suggestion would be more helpful. 任何建议都会更有帮助。

I'm not sure if parallelStream is what you're looking for here...you can also do this: 我不确定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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM