1

Suppose I have a situation where I call two Repositories to get items.

CompletableFuture<Optional<Account>> accountCompleteableFuture = CompletableFuture.supplyAsync(() ->AccountRepository.findById(accountId));

CompletableFuture<Optional<User>> userCompletableFuture = CompletableFuture.supplyAsync(() ->userRepository.findById(userId));

How Can I get a feedback when both are done brining back the results ? Traditionally I would call both one by one and then do the remaining logic. Here I want to speed up the process . I was trying to do something like thenCombine() ,but both are different Objects and I cannot write the logic in inside that lambda. Can any one suggest better way to do it?

Abhishek Sengupta
  • 2,938
  • 1
  • 28
  • 35

1 Answers1

3
CompletableFuture.allOf( groupCompletableFuture, userCompletableFuture ).join();
Davide D'Alto
  • 7,421
  • 2
  • 16
  • 30
  • Thanks for the answer, can you pls tell me the difference between the above and accountCompletableFuture.get() userCompletableFuture.get() – Abhishek Sengupta Apr 01 '21 at 14:36
  • They are the same but `join` doesn't throw any unchecked exceptions so you don't need a try - catch. – Davide D'Alto Apr 01 '21 at 14:40
  • one more question .. So while we create the CompletableFutures , it instantly executes the code right? even if we dont use the .get() on it right? – Abhishek Sengupta Apr 01 '21 at 14:51
  • 2
    @AbhishekSengupta nothing happens "instantly", it is _scheduled_ for execution, but you should not care about this - since you `join` waiting for the result anyway – Eugene Apr 01 '21 at 15:38
  • @Eugene So do you mean that It is scheduled for executing and is done automatically. So its not like that only when get() is called then only it start working. – Abhishek Sengupta Apr 01 '21 at 17:34
  • @AbhishekSengupta right, it is scheduled and starts execution. By the time your code reaches `get`, that `CompletableFuture` might be completed already. – Eugene Apr 01 '21 at 17:35
  • @Eugene this answer actually solved my doubts , Thanks man !!!!!! – Abhishek Sengupta Apr 01 '21 at 17:36
  • 1
    @AbhishekSengupta you are welcome, [you can read more details here](https://stackoverflow.com/questions/65605550/why-does-this-completablefuture-work-even-when-i-dont-call-get-or-join/65606195#65606195) for example. – Eugene Apr 01 '21 at 17:37