简体   繁体   中英

How to open and gather all the results from a list into threads with CompletableFuture?

I have a list of Strings, and for each of them, I need to open a new thread and to gather all the information into a CompletableFuture.

This is my iteration:

for (String result: results) {
    candidateInfos.add(getCandidatesInfo(result));
}

I am trying for the first time the implementation of threads and I would appreciate some help.

You can build Stream for each method call and can then collect the result into a list as follows.

Stream.Builder<Supplier<CanditateInfo>> streamBuilder = Stream.builder();
            
results.forEach(string-> streamBuilder.accept(() -> this.getCandidatesInfo(string)));
        
List<CanditateInfo> candidateInfos = streamBuilder.build().map(supplier -> CompletableFuture.supplyAsync(supplier, Executors.newFixedThreadPool(
  results.size()))).collect(Collectors.toList()).stream().map(
     CompletableFuture::join).collect(Collectors.toList());

Here I have used the separate Executor because by default, java use the common Fork and Join Pool which will block all other threads if the pool would have got filled. For more Info see http://fahdshariff.blogspot.in/2016/06/java-8-completablefuture-vs-parallel.html


Edit: Less syntax.

You can directly create a stream using a list or if you an array then using Arrays.stream instead of using Stream.Builder

           List<CanditateInfo> candidateInfos = results.stream().map(s ->
 CompletableFuture.supplyAsync(this.getCandidatesInfo(s), Executors.newFixedThreadPool(
           results.size()))).map(CompletableFuture::join).collect(Collectors.toList());

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