Just beginning to explore the reactor project and it's abstractions Mono and Flux and would like to understand the basic differences with the java 8 barebones CompletableFuture.
Here is a simple code I have:
public static void main(String[] args) throws Exception {
Mono.fromCallable(() -> getData())
.map(s -> s + " World ")
.subscribe(s -> System.out.println(s));
CompletableFuture.supplyAsync(() -> getData())
.thenAccept(System.out::println);
System.out.println(Thread.currentThread()+" End ");
}
private static String getData() {
int j=0;
for(int i=0; i<Integer.MAX_VALUE; i++){
j = j - i%2;
}
System.out.println(Thread.currentThread()+" - "+j);
return " Hello ";
}
Firstly, no surprises with the CompletableFuture
. supplyAsync
schedules the function for execution via the ForkJoinPool and the "End" line prints immediately and the program terminates as the main thread is really short-lived here - As expected.
But the Mono.fromCallable(...)
blocks the main thread there. Also, the thread name that gets printed in the getData()
function is the main thread. So I see a sequential/blocking behavior rather than sequential/nonblocking(async) behavior. Is it because I had applied a subscribe function on the same thread, it is blocking? Can someone explain this, please?