Scala 惰性值:性能损失?线程安全?
可能的重复:
惰性 val 的(隐藏)成本是多少? (斯卡拉)
Scala 允许定义惰性值
lazy val maybeUnusedValue = someCostlyInitialization
,其中仅在第一次使用 maybeUnusedValue
时评估 someCostlyInitialization
。也就是说,它最多被评估一次,如果从未使用过maybeUnusedValue,那么它也根本不会被评估。
这是线程安全的吗?这对性能有何影响? 如果这是线程安全的,它必须使用某种同步/以某种方式使用 Java 易失性。不幸的是,Scala 语言规范对此没有任何说明。
Possible Duplicate:
What's the (hidden) cost of lazy val? (Scala)
Scala allows the definition of lazy values
lazy val maybeUnusedValue = someCostlyInitialization
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用双重检查锁定使其成为线程安全的 http://code-o-matic.blogspot.com/2009/05/double-checked-locking-idiom-sweet-in.html 显然,这确实意味着访问惰性值比访问惰性值慢非懒惰者。
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.
更新:哎呀,正如瓦西尔指出的那样,这个问题是另一个线程的副本,而且碰巧的是,这个答案也是如此。
我参加了这门课程:
编译和反编译(使用 jd-gui):
正如您所看到的,它使用带有易失性变量的双重检查范例。所以我认为这是安全的
UPDATE: OOPS, as Vasil pointed out, the question is a copy of another thread, and as it happens, so is this answer.
I took this class:
Compiled and decompiled (with jd-gui):
As you can see it is using the double check paradigm with a volatile variable. So I think it is safe