Scala 惰性值:性能损失?线程安全? [英] Scala lazy values : performance penalty? Threadsafe?
问题描述
可能的重复:
惰性 val 的(隐藏)成本是多少?(斯卡拉)
Scala 允许定义惰性值
Scala allows the definition of lazy values
lazy val maybeUnusedValue = someCostlyInitialization
其中 someCostlyInitialization
仅在第一次使用 maybeUnusedValue
时进行评估.也就是说,它最多被评估一次,如果 maybeUnusedValue
从未被使用过,它也永远不会被评估.
where someCostlyInitialization
is evaluated only on the first use of maybeUnusedValue
. That is, it is evaluated at most once, and if maybeUnusedValue
is never used, it is also never evaluated at all.
这个线程安全吗?这对性能有什么影响?如果这是线程安全的,它必须以某种方式使用某种同步/使用 Java volatile.不幸的是,Scala 语言规范对此一无所知.
Is this threadsafe? What are the performance implications of this? If this is to be threadsafe, it has to use some kind of syncronization / use Java volatile in some way. Unfortunately the Scala language specification says nothing about this.
推荐答案
使用双重检查锁定使线程安全 http://code-o-matic.blogspot.com/2009/05/double-checked-locking-idiom-sweet-in.html 显然这确实意味着访问惰性 val 比非惰性 val 慢.
It is made thread-safe using double-checked locking http://code-o-matic.blogspot.com/2009/05/double-checked-locking-idiom-sweet-in.html Obviously this does mean that accessing lazy vals is slower than non-lazy ones.
这篇关于Scala 惰性值:性能损失?线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!