pau*_*aul 2 twitter scala finagle
有人可以解释我为什么 Twitter 未来的行为不是 Async?有这个代码
private val future: Future[String] = Future {
Thread.sleep(2000)
println(s"Running this effect in ${Thread.currentThread().getName}")
"Hello from Twitter"
}
println("Present")
Await.result(future)
Run Code Online (Sandbox Code Playgroud)
两秒后的输出是这个
Running this effect in main
Present
Run Code Online (Sandbox Code Playgroud)
所以未来是阻塞的,而不是在另一个线程中运行
Twitter 期货与 Scala 中的“标准”期货在语义上有些不同。
Future.apply实际上类似于标准Scala的Future.successful:它会创建一个Future是已经满足了-所以,你通过在块立即执行。
使用 Twitter Futures,您不需要在ExecutionContext任何地方隐式拖拽的烦人。相反,您有一个FuturePool显式地将代码传递给它以异步执行。例如:
val pool = FuturePool.unboundedPool
val future: Future[String] = pool {
Thread.sleep(2000)
println(s"Running this effect in ${Thread.currentThread().getName}")
"Hello from Twitter"
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,与 不同scala.concurrent,这Future是独立的:它“知道”管理它的池,因此,您无需随身携带它Future,以防万一有人需要做map或flatMap或某些其他转换就可以了。
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |