You can call the execution of method inside completable future and chain them all together. If I understood correctly here is how I tried to do it.
Completable:join
blocks until the execution is completed.
public class SimpleCompletableFutureSequence {
static class MyClass {
public String execute(String arg) {
// this will be otherwise lengthy operation
return arg;
}
public CalculatedTimedResponse executeAnother(String arg) {
LocalTime startTime = LocalTime.now();
LocalTime endTime = LocalTime.now();
MyClass myClass = new MyClass();
String response = null;
try {
response = myClass.execute(arg);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
endTime = LocalTime.now();
}
Duration timeDifference = Duration.between(startTime, endTime);
System.out.println("Difference: " + timeDifference.toSecondsPart());
return new CalculatedTimedResponse(timeDifference.toSecondsPart(), response);
}
}
static CompletableFuture<String> class1() {
return CompletableFuture.completedFuture(new MyClass().execute("class1"));
}
static CompletableFuture<String> class2() {
return CompletableFuture.completedFuture(new MyClass().execute("class2"));
}
static CompletableFuture<String> class3() {
return CompletableFuture.completedFuture(new MyClass().execute("class3"));
}
static CompletableFuture<String> class4() {
return CompletableFuture.completedFuture(new MyClass().execute("class4"));
}
public static void main(String[] args) {
List<CompletableFuture<String>> allFutures = Arrays.asList(class1(), class2(), class3(), class4());
List<String> allResponse = allFutures.stream().map(CompletableFuture::join).collect(Collectors.toList());
System.out.println(allResponse);
}
}
If you are planning to calculate the time difference, then here is how I trie to do it:
static class CalculatedTimedResponse {
int difference;
String response;
public CalculatedTimedResponse(int difference, String response) {
this.difference = difference;
this.response = response;
}
@Override
public String toString() {
return "CalculatedTimedResponse{" +
"difference=" + difference +
", response='" + response + '\'' +
'}';
}
}
And 2 completable futures
static CompletableFuture<CalculatedTimedResponse> class1Response = CompletableFuture.supplyAsync(new Supplier<CalculatedTimedResponse>() {
@Override
public CalculatedTimedResponse get() {
return new MyClass().executeAnother("time-execute- 1");
}
});
static CompletableFuture<CalculatedTimedResponse> class2Response = CompletableFuture.supplyAsync(new Supplier<CalculatedTimedResponse>() {
@Override
public CalculatedTimedResponse get() {
return new MyClass().executeAnother("time-execute- 2");
}
});
List<CompletableFuture<CalculatedTimedResponse>> timedFutures = Arrays.asList(class1Response, class2Response);
List<CalculatedTimedResponse> allTimeResponse = timedFutures.stream().map(CompletableFuture::join).collect(Collectors.toList());
System.out.println(allTimeResponse);
Source Code