java - 列表扩展的增量 future

标签 java concurrency future

我基本上有一个 Future<List<T>>从服务器批量获取。对于一些客户,我想在加载时提供增量结果,当 future 完成时,除了整个集合之外。

是否有为此定义的通用 Future 扩展?此类 future 存在哪些典型模式/组合器?

我假设给定 IncrementalListFuture<T>我可以轻松定义 map手术。您还想到什么?

最佳答案

Is there a common Future extension defined somewhere for this?

我假设您正在谈论来自 ExecutorService 的增量结果。您应该考虑使用 ExecutorCompletionService一旦其中一个 Future 对象可获取,您就会得到通知。

引用javadocs:

CompletionService<Result> ecs = new ExecutorCompletionService<Result>(e);
for (Callable<Result> s : solvers) {
    ecs.submit(s);
}
int n = solvers.size();
for (int i = 0; i < n; ++i) {
    // this waits for one of the futures to finish and provide a result
    Future<Result> future = ecs.take();
    Result result = future.get();
    if (result != null) {
        // do something with the result
    }
}

抱歉。我最初误读了这个问题,并认为您是在询问 List>。您可能可以重构您的代码以实际返回一些 Futures,所以我将把它留给后代。

在这种情况下,我不会在 Future 中传回列表。在工作完成之前,您将无法获得返回。

如果可能的话,我会在 中传递某种 BlockingQueue,这样调用者和线程都可以访问它:

final BlockingQueue<T> queue = new LinkedBlockingQueue<T>();
// build out job with the queue
threadPool.submit(new SomeJob(queue));
threadPool.shutdown();
// now we can consume from the queue as it is built:
while (true) {
   T result = queue.take();
   // you could some constant result object to mean that the job finished
   if (result == SOME_END_OBJECT) {
      break;
   }
   // provide intermediate results 
}

您还可以使用某种 SomeJob.take() 方法,它会调用在作业类中定义的 BlockingQueue

// the blocking queue in this case is hidden inside your job object
T result = someJob.take();
...

关于java - 列表扩展的增量 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12357265/

相关文章:

java - 如何使用 Java 对文本文件中的数字进行排序?

java - 当我通过 java 应用程序中的进程运行 pg_restore 时,应用程序卡住

java - 如何使用一个 WatchService 注册多个文件夹

java - 如果不中断,Future.cancel() 会做什么?

java - 调用同步方法的顺序

java - 无法获取元素的屏幕截图

c# - Task.WhenAll 为 Task<ConcurrentDictionary> 创建副本

JavaFX - 如何使用 UI Controller 事件暂停后台服务?

Future 的 Scala 命名约定

java - Future.get() 和 InterruptedException 异步线程