未来序列成功 [英] Flaky onSuccess of Future.sequence
问题描述
我写了这个方法:
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{ Success, Failure }
object FuturesSequence extends App {
val f1 = future {
1
}
val f2 = future {
2
}
val lf = List(f1, f2)
val seq = Future.sequence(lf)
seq.onSuccess {
case l => println(l)
}
}
我期望Future.sequence将List [Future]收集到Future [List]中,然后等待每个期货(在我的情况下为f1和f2)完成,然后在我的Future [List]序列上调用onSuccess情况.
I was expecting Future.sequence to gather a List[Future] into a Future[List] and then wait for every futures (f1 and f2 in my case) to complete before calling onSuccess on the Future[List] seq in my case.
但是在多次运行此代码后,它偶尔仅打印一次"List(1,2)",我不知道为什么它不能按预期工作.
But after many runs of this code, it prints "List(1, 2)" only once in a while and I can't figure out why it does not work as expected.
推荐答案
尝试一次,
import scala.concurrent._
import java.util.concurrent.Executors
import scala.util.{ Success, Failure }
object FuturesSequence extends App {
implicit val exec = ExecutionContext.fromExecutor(Executors.newCachedThreadPool)
val f1 = future {
1
}
val f2 = future {
2
}
val lf = List(f1, f2)
val seq = Future.sequence(lf)
seq.onSuccess {
case l => println(l)
}
}
这将始终打印List(1,2)
.原因很简单,上面的exec
是线程(不是守护程序线程)的ExecutionContext,其中在您的示例中,ExecutionContext是从ExecutionContext.Implicits.global
隐式获取的默认值,其中包含守护程序线程.
This will always print List(1,2)
. The reason is simple, the exec
above is an ExecutionContext of threads (not daemon threads) where as in your example the ExecutionContext was the default one implicitly taken from ExecutionContext.Implicits.global
which contains daemon threads.
因此是守护程序,该过程无需等待seq
将来完成并终止.如果seq
完全完成,那么它将打印.但这并不总是会发生
Hence being daemon, the process doesn't wait for seq
future to be completed and terminates. if at all seq
does get completed then it prints. But that doesn't happen always
这篇关于未来序列成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!