In this basic example of CompletableFuture, I run a task asynchronously and when it's finished, an async callback should be triggered.
One second after I start running the task, and before it's finished, I complete it. After that I don't see it running the asynchronous callback anymore.
public static void main(String[] args) throws InterruptedException {
runTask();
Thread.sleep(1000);
completableFuture.complete("Test");
Thread.sleep(4000);
}
public static void runTask() {
completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("Running...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("...finished");
return "finished task";
})
.thenApplyAsync(s -> {
System.out.println("Apply on result: " + s);
return "Result: " + s;
})
}
The result of this is:
Running...
...finished
The thing is that if I add another callback, then it runs the first one but not the second one.
.thenApplyAsync(s -> {
System.out.println("Second apply with result: " + s);
return "Result: " + s;
})
Then the result is:
Running...
...finished
Apply on result: finished task
Reading the documentation I understood all the callbacks would be always called, even if the future is completed manually. Am I missing something here?