首页 > 解决方案 > 在 Java 8 中等待任何未来,而不为每个未来创建线程

问题描述

我有一个期货集合,我想等待其中的任何一个,这意味着有一个阻塞调用,一旦任何未来完成,就会返回。

我看到了,CompletableFuture.anyOf()但是如果我正确理解了它的代码,它会为每个未来创建一个线程,如果在 Java 中可能的话,我想在资源方面使用一种不那么浪费的方法。

标签: javajava-8future

解决方案


直接的答案是肯定的,这是一个示例方法

    private <T> CompletableFuture<T> waitAny(List<CompletableFuture<T>> allFutures) throws InterruptedException {
        Thread thread = Thread.currentThread();
        while (!thread.isInterrupted()) {
            for (CompletableFuture<T> future : allFutures) {
                if (future.isDone()) {
                    return future;
                }
            }
            Thread.sleep(50L);
        }
        throw new InterruptedException();
    }

第二种选择

    private <T> CompletableFuture<T> waitAny(List<CompletableFuture<T>> allFutures) throws InterruptedException {
        CompletableFuture<CompletableFuture<T>> any = new CompletableFuture<>();
        for (CompletableFuture<T> future : allFutures) {
            future.handleAsync((t, throwable) -> {
                any.complete(future);
                return null;
            });
        }
        try {
            return any.get();
        } catch (ExecutionException e) {
            throw new IllegalStateException(e);
        }
    }

但任务的整个背景尚不清楚,可能有更优化的解决方案。


推荐阅读