1
\$\begingroup\$

I currently have some code in Java which looks something like this, but I want to refactor this.

List<Object> combinedStatus = new ArrayList();
for (List<Long> batch: batches){
    CompletableFuture<Object> future = ask();
    futureHolder.add(future);
}

try {
   for (CompletableFuture<Object> future: futureHolder) { 
      response = future.get();
      combinedStatus.add(response.result());
   } catch (Exception e) {
       // log exception 
   }
return combinedStatus;

I see one major issue is that future.get() is blocking the thread. I want to refactor this to make it non blocking. Here is my refactored version - can someone give me some advice on if this is correct / makes sense / or how I can make this better?

for (List<Long> b: batches) {
   CompletionStage<Object> stage = ask();
    stage.whenComplete(
        (resp, ex) -> {
            if (ex != null) {
             // log exception 
           } else { 
               combinedStatus.add(response.result());
     });
}

returned combinedStatus;

Additionally, can someone explain to me what is the behavior of this if I call this in a loop

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.