How to identify / get automated hints with cyclic object initialization causing deadlocks in Scala?

前端 未结 1 1715
暖寄归人
暖寄归人 2021-01-26 04:19

The following code runs into future timeouts (in Scala 2.x and Dotty, -Xcheckinit or -Ycheck-init does not help here) because of cyclic object initialization. In complex project

相关标签:
1条回答
  • 2021-01-26 04:53

    In general, the compiler and JVM will not help you avoid this.

    The best you can do to address this is delay evaluation of the cycle by, for instance:

    • using lazy val
    • using def

    Note that either results in some overhead relative to a simple val. I haven't done experiments, but I'd suspect that lazy val (incurring the expense of some synchronization) is better for a case like

    lazy val all = Set(Left, Right)
    

    to limit allocations of redundant objects, and that def is better for a case like

    def basePath = Base.LeftElement
    

    since that's pretty likely to be inlined by JIT.

    See also: How to diagnose or detect deadlocks in static initializers

    0 讨论(0)
提交回复
热议问题