Reputation: 309
I need some advices, if you please. I need to call a couple of async services in parallel, from my spring application. I mean: the code should be as slow as the slowest async task
I have coded it in the following way, but I'm not very sure if this is the best way. Probably not xD. In fact, I'm not very used to the java8 lambdas and streams stuff, so I could be a point of improvement.
```
@Service
@Qualifier("service1")
public class Service1 implements IService {
@Async("processExecutor")
public AsyncResult<MyResult> doStuff(Stuff input){
return new AsyncResult<Optional<MyResult>>(callStuff(input));
}
}
@Service
@Qualifier("service2")
public class Service2 implements IService {
@Async("processExecutor")
public AsyncResult<MyResult> doStuff(Stuff input){
return new AsyncResult<Optional<MyResult>>(callStuff(input));
}
}
@Service
@Qualifier("service3")
public class Service3 implements IService {
@Async("processExecutor")
public AsyncResult<MyResult> doStuff(Stuff input){
return new AsyncResult<Optional<MyResult>>(callStuff(input));
}
}
And then, in another spring service I have the following stuff:
```
AsyncResult<MyResult>aResult1=service1.doStuff(input);
AsyncResult<MyResult>aResult2=service2.doStuff(input);
AsyncResult<MyResult>aResult3=service3.doStuff(input);
MyResult result1= aResult1.get();
MyResult result2= aResult2.get();
MyResult result2= aResult3.get();
Would you point me in the right direction, if you please?
Thanks a lot in advance!
Upvotes: 2
Views: 8051
Reputation: 312
You may want to use CompletableFuture.allOf
CompletableFuture<MyResult> futur1=CompletableFuture.supplyAsync( ()->{return service1.doStuff(input);});
CompletableFuture<MyResult> futur2=CompletableFuture.supplyAsync( ()->{return service2.doStuff(input);});
CompletableFuture<MyResult> futur3=CompletableFuture.supplyAsync( ()->{return service3.doStuff(input);});
CompletableFuture<Void> allCompleted = CompletableFuture.allOf(futur1,futur2,futur3);
allCompleted.get();// this one will block current thread until futur1,futur2,futur3 done.
MyResult r1 = futur1.get();
MyResult r2 = futur2.get();
MyResult r3 = futur3.get();
Upvotes: 6