简体   繁体   中英

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.?

I skimmed through few blogs about CompletableFuture but not sure will it help my scenario.

Any suggestion would be more helpful.

I'm not sure if parallelStream is what you're looking for here...you can also do this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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