【发布时间】:2014-04-19 12:42:55
【问题描述】:
我想知道是否有办法缓存 Futures 以便在它们完成时使用。例如,我有一个主线程,它产生一个从输入流中读取的执行器:
// pseudo code
while(true){
Callable task = new Callable({
// setup callable stuff here
byte[] call(){
return inputStream.readInBytes();
}
});
Future f = executors.submit(task);
byte[] b = f.get(); // blocks Uggh
// execute of b
process(b);
}
我想知道是否有办法将期货放入一个集合中,然后在它们完成时进行处理。
// pseudo code
while(true){
Callable task = new Callable({
// setup callable stuff here
byte[] call(){
return inputStream.readInBytes();
}
});
Future f = executors.submit(task);
futures.add(f);
// process bytes as they completed.
for(Future f: futures){
if(f.isDone()){ // this doesn't always return valid. It sometimes throws NPE's
b = f.get();
process (b);
}
}
}
我已经尝试了第二个代码片段,但它有时会抛出 NPE - 我假设在刚刚启动的线程上调用了“isDone”方法,这是问题所在(猜测)。
有人知道在期货开始完成之前缓存期货的方法吗?现在我的程序连续运行,但我正在寻找优化和加速它的方法。
谢谢
【问题讨论】:
-
删除了我对
Byte的使用,并将它们改为byte -
看看 Java8 中的 CompletableFuture()。这不是最容易实现的技术
标签: java multithreading caching collections concurrency