【发布时间】:2010-11-17 18:31:27
【问题描述】:
Future 非常方便,但在实践中,您可能需要对其执行进行一些保证。例如,考虑:
import scala.actors.Futures._
def slowFn(time:Int) = {
Thread.sleep(time * 1000)
println("%d second fn done".format(time))
}
val fs = List( future(slowFn(2)), future(slowFn(10)) )
awaitAll(5000, fs:_*)
println("5 second expiration. Continuing.")
Thread.sleep(12000) // ie more calculations
println("done with everything")
这个想法是并行启动一些运行缓慢的函数。但是,如果期货执行的函数没有返回,我们不希望永远挂起。所以我们使用 awaitAll() 来设置期货的超时时间。但是,如果您运行代码,您会看到 5 秒计时器到期,但 10 秒未来继续运行并稍后返回。超时不会杀死未来;它只是限制了加入等待。
那么你如何在超时后杀死一个未来?除非您确定它们会在已知的时间内返回,否则似乎无法在实践中使用期货。否则,您将冒着将线程池中的线程丢失到非终止future 的风险,直到没有线程为止。
所以问题是:你如何杀死期货?考虑到这些风险,期货的预期使用模式是什么?
【问题讨论】:
标签: scala