Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do we ensure that completableFuture operations are done concurrently? #341

Open
wjiayis opened this issue Nov 29, 2022 · 2 comments
Open

Comments

@wjiayis
Copy link

wjiayis commented Nov 29, 2022

Hi there,

Say there is a procedure as such:
Steps 1-3 are independent.
Step 4 requires steps 1-3.
Output requires steps 1, 2, 4.

May I check what functions I should call for each step so that I don't repeat computation, while ensuring that they are done with minimal total duration?

I was thinking of performing steps 1-4 using separate thenCombine(), then call join() for steps 1, 2 and 4. But I'm not sure if this would mean steps 1-2 are computed twice. I am also not sure if steps 1-3 will indeed be performed asynchronously in this procedure.

Would appreciate some help, and thanks in advance.

@wjiayis wjiayis changed the title How do we ensure that completedFuture operations are done concurrently? How do we ensure that completableFuture operations are done concurrently? Nov 29, 2022
@liewyungjun
Copy link

you can do CompletableFuture.supplyAsync(...) to run steps 1-3. I think for step 4 you can use either a chained thenCombine or a nested thenCombine, or even the allOf method to get steps 1-3 for 4.

when you call the join() method it doesnt evaluate twice, it just returns the previously computed value fo the CompletableFuture so you can just call .join() for the final return for steps 1,2,4

@FredericChow00
Copy link

FredericChow00 commented Nov 29, 2022

Basically when you assign CompletableFutures as a type to a variable, you are saying that this variable will be done (sometime in the future)

For your example, the only part that can be parralized are operations 1-3, if I'm understanding it correctly. Since the very last operation requires 4 to be completed, where 4 can ONLY be executed after 1-3, then the last operation will definitely wait for 4 to finish first, which requires 1-3 to be finished.

So you can actually just do supplyAsync() for each of 1-3 then followed by creating another CF for allOf(1,2,3) followed by thenApply(4) then finally output the result of 4.

But do remember to call .join() after the ...thenApply(4) to ensure that the output actually waits for 4 to finish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants