繁体   English   中英

等待 Java 8 中的任何未来,而不为每个未来创建线程

[英]Wait on any future in Java 8 without creating thread per future

我有一组期货,我想等待它们中的任何一个,这意味着有一个阻塞调用,一旦完成任何期货,它就会返回。

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

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

    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);
        }
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM