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
@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() ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With