Playing around with CompletableFutures and I coincided these outputs that I am not able to make sense of. I will share two snippets which should behave same in my perception. But they are not.
So the first program goes like:
public static void main(String... args) {
for (int i = 0; i < 5; i++) {
CompletableFuture.supplyAsync(() -> Thread.currentThread().getName())
.thenApply(threadName -> {
delay();
List<String> parsedName = Arrays.stream(threadName.split("-")).toList();
return parsedName.get(parsedName.size() - 1);
})
.thenAcceptAsync(System.out::println);
}
}
static void delay() {
try {
Thread.sleep(1000);
} catch(InterruptedException ignored) {
System.out.println("Interrupted");
}
}
The output for this program is:
1
Where as the second program writes the completablefutures without the for loop, again 5 times:
public static void main(String... args) {
CompletableFuture.supplyAsync(() -> Thread.currentThread().getName())
.thenApply(threadName -> {
delay();
List<String> parsedName = Arrays.stream(threadName.split("-")).toList();
return parsedName.get(parsedName.size() - 1);
})
.thenAcceptAsync(System.out::println);
CompletableFuture.supplyAsync(() -> Thread.currentThread().getName())
.thenApply(threadName -> {
delay();
List<String> parsedName = Arrays.stream(threadName.split("-")).toList();
return parsedName.get(parsedName.size() - 1);
})
.thenAcceptAsync(System.out::println);
CompletableFuture.supplyAsync(() -> Thread.currentThread().getName())
.thenApply(threadName -> {
delay();
List<String> parsedName = Arrays.stream(threadName.split("-")).toList();
return parsedName.get(parsedName.size() - 1);
})
.thenAcceptAsync(System.out::println);
CompletableFuture.supplyAsync(() -> Thread.currentThread().getName())
.thenApply(threadName -> {
delay();
List<String> parsedName = Arrays.stream(threadName.split("-")).toList();
return parsedName.get(parsedName.size() - 1);
})
.thenAcceptAsync(System.out::println);
CompletableFuture.supplyAsync(() -> Thread.currentThread().getName())
.thenApply(threadName -> {
delay();
List<String> parsedName = Arrays.stream(threadName.split("-")).toList();
return parsedName.get(parsedName.size() - 1);
})
.thenAcceptAsync(System.out::println);
}
static void delay() {
try {
Thread.sleep(1000);
} catch(InterruptedException ignored) {
System.out.println("Interrupted");
}
}
The output of this program is consistently:
1
1
1
1
1
I do not really understand why the first program with for loop does not print out anything even though two programs look identical semantically(in my eyes). Thank you, looking forward to replies.
Mehmet Atakan Serin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.