currently i have a requirement to make async task to sync in completablefuture. Eg. Task A and Task B are completablefuture. Task B runs when Task A is completed. This works fine for single time. Suppose if I make it to run in foor loop, obviously it will create n number of async calls to achieve the outcome. Because of this, i'm getting o/p like below
A
B
A
A
B
B
A
B
A
A
A
I want to achieve like
A
B
A
B
A
B
A
B
Here is the code,
package com.demo.completable.combine;
import javax.xml.stream.Location;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThenCompose {
synchronized CompletableFuture<User> getUserDetails(String name) {
return CompletableFuture.supplyAsync(() -> {
return UserService.getUser(name);
});
}
synchronized CompletableFuture<Double> getRating(User user) {
return CompletableFuture.supplyAsync(() -> {
return CreditRating.getCreditRating(user);
});
}
synchronized CompletableFuture<String> getResult(Double rating) {
return CompletableFuture.supplyAsync(()-> {
return "welcome world";
});
}
public void main() throws InterruptedException, ExecutionException {
ThenCompose cc = new ThenCompose();
// then apply
CompletableFuture<CompletableFuture<Double>> result = cc.getUserDetails("kumaran").thenApply(user -> {
return cc.getRating(user);
});
// then compose
for (int i = 1; i <= 15; i++) {
CompletableFuture<Double> taskA = cc.getUserDetails("mike").thenCompose(user -> {
System.out.println("Task A --- " +Thread.currentThread().getName() + "--" + LocalTime.now());
return cc.getRating(user);
});
CompletableFuture<String> fileLocation =
taskA.thenCompose(ts -> {
System.out.println("Task B --- " +Thread.currentThread().getName() + "--- " + LocalTime.now());
return getResult(ts);
});
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThenCompose tc = new ThenCompose();
tc.main();
}
}
putting join and get will work but I'm not supposed to use both join and get. kindly suggest a solution.