简体   繁体   English

在Android中双重检查锁定

[英]Double checked locking in Android

According to many, the somewhat common Double-Checked Locking idiom is broken for java unless you're running 1.5 or later and use the volatile keyword. 根据许多人的说法,除非你运行1.5或更高版本并使用volatile关键字,否则对于java来说,有些常见的Double-Checked Locking成语已被破坏。

A broken double-checked lock sample: 一个破损的双重检查锁定样本:

// Broken multithreaded version
// "Double-Checked Locking" idiom
class Foo { 
  private Helper helper = null;
  public Helper getHelper() {
    if (helper == null) 
      synchronized(this) {
        if (helper == null) 
          helper = new Helper();
      }    
    return helper;
    }
  // other functions and members...
  }

The sample comes from this article, which also provides details on how to fix it: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html 该示例来自本文,其中还提供了有关如何修复它的详细信息: http//www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

Pugh's analysis above is for Java VMs. Pugh上面的分析是针对Java VM的。 I work on Android and frequently use libraries that employ Double-Checked Locking. 我在Android上工作并经常使用采用Double-Checked Locking的库。 Does the dalvik VM's memory model support this idiom? dalvik VM的内存模型是否支持这个习惯用法?

这个问题的答案意味着内存模型应该是相同的,并且新的双重检查锁定习惯将起作用。

I found a very good article about that question : http://www.javamex.com/tutorials/double_checked_locking_fixing.shtml 我发现了一篇关于这个问题的非常好的文章: http//www.javamex.com/tutorials/double_checked_locking_fixing.shtml

It clearly states 3 ways to fix DCL. 它清楚地说明了3种修复DCL的方法。 And it looks like in your question, the Helper field should be declared volatile, otherwise it doesn't work. 看起来在你的问题中,Helper字段应该被声明为volatile,否则它不起作用。

When it comes to usage, ie RoboGucie in your case, I think I would favor the class loader method mentionned in the article. 在使用方面,即你的RoboGucie,我想我会赞成文章中提到的类加载器方法。 It's more clear to me and as efficient. 这对我来说更清楚,也更有效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM