我基本上有一个 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
在这种情况下,我不会在 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/