2020年12月31日星期四

Java run loop with CompletableFuture

I am trying to use CompletableFuture to execute for loop in parallel. And inside the loop I use supplyAsync to call doSomething to get output string and then put it in HashMap:

    ...      ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();      CompletableFuture<?> completableFuture = null;        for ( int i = 0; i < numberOfRecords; i++ ) {          final int finalI = i;          completableFuture = CompletableFuture                  .supplyAsync( () -> doSomething( data, finalI ) )                  .thenAccept( str -> map.put( finalI, str ) );      }      completableFuture.join();    private String doSomething(HashMap<String, String> data, int finalI ) ) {      ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();        for ( int k = 0; k < data.size(); k++ ) {      //process data and add it in queue      }      String result = processQueueAndReturnString(queue);      return result;     

The problem is when for loop is almost done ( when i is close to numberOfRecords), another for loop inside doSomething method skips some iterations, e.g. if k=5 it can run loop only until k=2 or 3 and in this case supplyAsync( () -> doSomething( data, finalI ) ) returns null. So it seems like my for loop with CompletableFuture finishes until some iterations are completely done.

Any suggestions or hints on how to fix that?

https://stackoverflow.com/questions/65526122/java-run-loop-with-completablefuture January 01, 2021 at 06:55AM

没有评论:

发表评论