I am trying to understand the working of CompletableFuture
from Java 8. Below code works as expected
CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync Thread name " + Thread.currentThread().getName());
return "str";
}).thenApply(str -> {
System.out.println("thenApply Thread name " + Thread.currentThread().getName());
return str;
}).thenApply(str1 -> {
System.out.println("thenApply Thread name " + Thread.currentThread().getName());
return str1;
}).thenAccept(str3 -> {
System.out.println("thenAccept Thread name " + Thread.currentThread().getName());
});
System.out.println("Thread name " + Thread.currentThread().getName());
Output:
supplyAsync Thread name ForkJoinPool.commonPool-worker-1
thenApply Thread name main
thenApply Thread name main
thenAccept Thread name main
Thread name main
But when I put in some computation, it doesn't work as expected please correct me if I am missing something.
CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync Thread name " + Thread.currentThread().getName());
long val = 0;
for (long i = 0; i < 1000000; i++) {
val++;
}
return "str";
}).thenApply(str -> {
System.out.println("thenApply Thread name " + Thread.currentThread().getName());
long val = 0;
for (long i = 0; i < 1000000; i++) {
val++;
}
return str;
}).thenApply(str1 -> {
System.out.println("thenApply Thread name " + Thread.currentThread().getName());
long val = 0;
for (long i = 0; i < 1000000; i++) {
val++;
}
return str1;
}).thenAccept(str3 -> {
System.out.println("thenAccept Thread name " + Thread.currentThread().getName());
long val = 0;
for (long i = 0; i < 1000000; i++) {
val++;
}
});
System.out.println("Thread name " + Thread.currentThread().getName());
Output is:
supplyAsync Thread name ForkJoinPool.commonPool-worker-1
Thread name main
I agree that I am not joining the child thread to main thread. My understanding is child thread should print the statements independently of main thread. The question is why is it not printing at all.