Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is completedFuture according to below code will trigger two items in same time?

i need to run two items in same time asynchronous According to below scenario, i feel a bit confused if the two of items are triggered in same time or sequentially i mean after each user completed then next one is triggered or what is actually happen in background?

Caller method supposed to accept a list of two items

What i did is like that

@Async
public CompletableFuture<User> runTwoInSameTime(String userName) {
        User user = getUserDetails(userName);
        return CompletableFuture.completedFuture(user );
    }

public void caller(List<User> users){
List<CompletableFuture<User>> completableFutures = v.stream().map((user) -> {
                return runTwoInSameTime(user.getName);
            }).collect(Collectors.toList());
}

if it's sequential so is this change can make them triggred in same time ?

@Async
public CompletableFuture<User> runTwoInSameTime(String userName) {
        User user = getUserDetails(userName);
        return CompletableFuture.supplyAsync(() -> user);
    }

and changed stream to parallelStream() ?

like image 791
dev_2020 Avatar asked Jan 25 '26 08:01

dev_2020


1 Answers

I suppose you want the getUserDetails() method to run asynchronously. As you're currently calling it, it's running in the caller's thread.

Both your current code and the fix you have suffer from the same problem. Changing it to this will run the method asynchronously:

public CompletableFuture<User> runTwoInSameTime(String userName) {
    return CompletableFuture.supplyAsync(() -> getUserDetails(userName));
}

Code that runs in CompletableFuture.supplyAsync is executed asynchronously, not code that is executed before.

Just a side note: when you collect a List<CompletableFuture<User>> object, you should be aware that this is a list of futures representing potentially running (not completed) tasks. You may need to run through the list and call join() on each element after collecting. to be sure that your getUserDetails method has completed for each call.

like image 87
ernest_k Avatar answered Jan 27 '26 22:01

ernest_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!