Using CompletableFuture in Java, I realized that using thenAccept or other sync methods over a CompletableFuture is very tricky in the next way as documented in this website: https://mobiarch.wordpress.com/2018/09/07/understanding-java-completablefuture/. I quote verbatim:
Things are not so simple for the non-async methods like thenAccept. Java uses this policy: If the future for which thenAccept() is called has already completed prior to the call then the lambda will be called in the same thread that called thenAccept(). If the future has not completed yet when thenAccept() is called then the lambda will be called in the same thread where the future is completed. That will be a thread from the default ForkJoinPool in our case". Basically the non-Async methods try to avoid any unnecessary thread switching. This has less CPU overhead and works faster. But if the lambda takes a long time to complete we risk blocking the main thread.
I think this is a very unexpected behaviour, not well documented and tricky because I created some CompletableFuture to run an async task in order to return something from it and wait for this task to finish using thenAccept and with a lambda function getting the result to return to the client. But the lambda function did not execute in the main Thread causing to return some default value to the client and not the calculated one.
This is happening because I used lambda functions?
Why is this so tricky?
Is the JRE the one is causing this behaviour and not the code itself?
Thanks