由于循环对象初始化,以下代码会遇到未来的超时(在 Scala 2.x 和 Dotty 中,-Xcheckinit 或 -Ycheck-init 在这里没有帮助)。在复杂的项目中,这些周期通常隐藏得很好。是否有可能从编译器或至少在运行时获得帮助?在多线程环境中如何防止这种情况发生?
import scala.concurrent.Future
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
object Base {
val LeftElement = "Left"
val RightElement = "Right"
println("Base before: " + Thread.currentThread())
val all = Set(Left, Right)
println("Base after: " + Thread.currentThread())
}
object Left {
println("Left before: " + Thread.currentThread())
val basePath = Base.LeftElement
}
object Right {
println("Right before: " + Thread.currentThread())
val basePath = Base.RightElement
}
object Main extends App {
val f1 = Future(Left)
val f2 = Future(Right)
println(Await.result(f1, 1 second))
println(Await.result(f2, 1 second))
}