我有一个长期运行的Scala Future
,其操作如下:
计算初始结果
改善结果
如果没有改善,则终止,否则转到2
收到外部信号(这意味着Future
不会知道应该运行多长时间)后,我希望能够告诉Future
终止并给我其中间结果。我可以使用某种辅助渠道来做到这一点(注意:这是一个使用Akka
的Java程序,因此之所以要在Java中创建Scala Future以及所有附带的样板)是这样的:
public void doCalculation(AtomicBoolean interrupt, AtomicReference output) {
Futures.future(new Callable<Boolean>() {
public Boolean call() {
Object previous = // calculate initial value
output.set(previous);
while(!interrupt.get()) {
Object next = // calculate next value
if(/* next is better than previous */) {
previous = next;
output.set(previous);
} else return true;
}
return false;
}
}, TypedActor.dispatcher());
}
这样,无论谁调用
doCalculation
,都可以通过output
获得中间值,并可以通过Future
终止interrupt
。但是,我想知道是否有一种方法可以不使用辅助通道,因为这会使其他人很难维护我的代码。我们正在使用Java 7。 最佳答案
在我看来,这听起来不太像Future
。相反,请考虑仅更新Runnable
字段的AtomicReference
。您的runnable可以根据需要频繁地更新引用,并且调用者可以在需要时轮询该字段。
如果希望类实现Supplier
公开用于获取值的标准接口,则可以使它实现。