Scala 惰性值:性能损失?线程安全?

发布于 2024-09-30 06:07:47 字数 600 浏览 5 评论 0原文

可能的重复:
惰性 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

走过海棠暮 2024-10-07 06:07:47

使用双重检查锁定使其成为线程安全的 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.

肥爪爪 2024-10-07 06:07:47

更新:哎呀,正如瓦西尔指出的那样,这个问题是另一个线程的副本,而且碰巧的是,这个答案也是如此。

我参加了这门课程:

class Foo {
  lazy val test = "hi"
}

编译和反编译(使用 jd-gui):

public class Foo
  implements ScalaObject
{
  private String test;
  public volatile int bitmap$0;

  public String test()
  {
    if (
      (this.bitmap$0 & 0x1) == 0);
    synchronized (this)
    {
      if (
        (this.bitmap$0 & 0x1) == 0) {
        this.test = "hi"; this.bitmap$0 |= 1; } return this.test;
    }
  }
}

正如您所看到的,它使用带有易失性变量的双重检查范例。所以我认为这是安全的

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:

class Foo {
  lazy val test = "hi"
}

Compiled and decompiled (with jd-gui):

public class Foo
  implements ScalaObject
{
  private String test;
  public volatile int bitmap$0;

  public String test()
  {
    if (
      (this.bitmap$0 & 0x1) == 0);
    synchronized (this)
    {
      if (
        (this.bitmap$0 & 0x1) == 0) {
        this.test = "hi"; this.bitmap$0 |= 1; } return this.test;
    }
  }
}

As you can see it is using the double check paradigm with a volatile variable. So I think it is safe

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文