Nested Futures not executing

こ雲淡風輕ζ 提交于 2019-12-01 22:40:09

The reason why this doesn't work is because in your simple test the VM exits before all tasks are completed.

When you call completableFutureCompletableFuture.get() only the first nesting of the futures is guaranteed to have finished. The VM exits, and all threads get killed.

In other words, the first nested future could still be "uncompleted" as its thread might still be busy. However, when you try to get its result with get it will of course wait until it completed and it will work as expected. Just try:

completableFutureCompletableFuture.get().get().get().get().get()

... then you force all futures to have completed and everything works as expected.

Just tested this and it works. I think the reason why is not working for you is because you run in in a main method and you did not wait to complete. I did a Thread.sleep(1000) after your code and it worked. The best way would be to wai for termination: completableFutureCompletableFuture.get().get().get().get().get()

It happens because your CompletableFuture are executed asynchronously but your program terminates before the fifth call happens (I assume you ran it in a single main and returned just after creating your futures).

As you may not know how many Future are stacked in your Future (due to type erasure). You may want to perform a recursive .get().

See :

public static void main(String[] args) throws InterruptedException, ExecutionException {

    CompletableFuture<?> futures = getFutures();
    recursiveGet(futures);
    System.out.println("finished");

}

public static CompletableFuture<?> getFutures() {
    CompletableFuture<CompletableFuture<CompletableFuture<CompletableFuture<CompletableFuture<CompletableFuture<Object>>>>>> compositeCompletable = CompletableFuture.supplyAsync(() -> {
        System.out.println("first");
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("second");
            return CompletableFuture.supplyAsync(() -> {
                System.out.println("third");
                return CompletableFuture.supplyAsync(() -> {
                    System.out.println("fourth");
                    return CompletableFuture.supplyAsync(() -> {
                        System.out.println("fifth");
                        return CompletableFuture.completedFuture(null);
                    });
                });
            });
        });
    });
    return compositeCompletable;
}

public static void recursiveGet(Future<?> future) throws InterruptedException, ExecutionException{
    Object result = future.get();
    if(result instanceof Future){
        recursiveGet((Future<?>) result);
    }
}

which returns

first
second
third
fourth
fifth
finished
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!