Asif Ansari
Asif Ansari

Reputation: 93

What is best way to process multiple Async operation and handle each for further processing?

In my project, there is a method with return type List of Future. This other developer has iterated over for loop as such

public List<Future<Object>> method1(){
    List<Future<Object>> lists = new ArrayList();
    for(MultipartFile file : files){
      Future<Object> future = service.method2(file);
      lists.add(future);
    }
   return lists;
}

Now i have to perform certain operations on Object of a list as soon as it is processed. How i do this? Even if i put a for loop like

for(Future<Object> future : lists){
  if(future.isDone()){
       performOtherOperation(future.get());
  }
}

If first object is not processed, the isDone() condition will fail and it will be ignored and 2nd iteration will start, how can i process this?

Can this be also done using ExecutorService?? i am not familiar with ExecutorService.

Edit : So i edited the method2(File) of service class from

public Future<Object> method2(File){
  object = operation();
  return new AsyncResult(object);
}

to public CompletableFuture method2(File);

But what is the return type i should choose which is equivalent to AsyncResult. AsyncResult is an implementation of Spring framework.

I can't modify this code until i am 100% sure it will not break existing multithreading performance or degrade it.

Upvotes: 2

Views: 590

Answers (1)

MikeFHay
MikeFHay

Reputation: 9023

If you can change service.method2 to return a CompletableFuture, then the problem becomes trivial:

for(CompletableFuture<Object> future : lists){
  future.whenComplete((obj, err) -> performOtherOperation(obj));
}

If you absolutely can't modify method2, then you could convert the Future objects to CompletableFutures as described in Transform Java Future into a CompletableFuture

Upvotes: 2

Related Questions