java - 在 Java 8 中等待任何未来,而不为每个未来创建线程
问题描述
我有一个期货集合,我想等待其中的任何一个,这意味着有一个阻塞调用,一旦任何未来完成,就会返回。
我看到了,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);
}
}
但任务的整个背景尚不清楚,可能有更优化的解决方案。
推荐阅读
- mysql - Mysql:尽管文件内容包含数据,但最终字段中的空字段
- amazon-web-services - MongoDB BSON 文档在 Flask 应用程序上出现太大错误,但在独立执行时运行良好
- virtualbox - Vagrant up 返回错误
- python - Python/Pandas:仅当每个 Excel 文件包含某些值时才循环附加 Excel 文件
- c# - Xamarin.iOS 无法从引用的 System.Drawing.Common 中识别“位图”类型
- ios - Swift 中的“文件夹‘文档’不存在”错误
- python - 获取目录中所有 mp3 文件的持续时间。
- react-native - 用 cookie 反应原生图像 uri 请求
- jquery - 一次只展开一个引导程序 4 折叠
- android - 在我的 android 应用程序中以响应方式显示文档内容