Search code examples
javamultithreadingjava-8completable-future

When do CompletableFutures in JDK8 block the execution threads?


Example 1:

CompletableFuture
    .supplyAsync(new MySupplier())
    .someCompletableFutureMethod(new SomeCompletableFutureComsumer())

Does the ForkJoin thread ever get blocked?

Example 2:

final CompletableFuture cf = new CompletableFuture();
cf = executor.execute(new Runnable() {
    public void run() {
        //do work
        cf.complete(result);
    }
});
cf.whenComplete(new MyConsumer());

Do any of the treads involved ever get blocked?

( I know, I should use Callable instead of Runnable :)

Is there any way I can misuse the API without using the method inherited from Future to block any thread (main, ForkJoin, executor)?

Assuming I am not using any blocking APIs (I know future.get() blocks).


Solution

  • CompletableFuture adds the join() method, which is kind of a non-checked exception version of Future.get() (docs here). I don't recommend using it though because, by not taking a timeout, it can hang the thread and you can almost always rewrite the code using thenApply and friends. I try to enforce this by always using CompletionStage, which CompletableFuture implements.

    I don't think any other methods except the ones inherited from Future block.