Double checked locking in Android

青春壹個敷衍的年華 提交于 2020-01-11 17:08:14

问题


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.

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

Pugh's analysis above is for Java VMs. I work on Android and frequently use libraries that employ Double-Checked Locking. Does the dalvik VM's memory model support this idiom?


回答1:


The answer to this question implies that the memory models should be the same, and that the new double checked locking idiom will work.




回答2:


I found a very good article about that question : http://www.javamex.com/tutorials/double_checked_locking_fixing.shtml

It clearly states 3 ways to fix DCL. And it looks like in your question, the Helper field should be declared volatile, otherwise it doesn't work.

When it comes to usage, i.e. RoboGucie in your case, I think I would favor the class loader method mentionned in the article. It's more clear to me and as efficient.



来源:https://stackoverflow.com/questions/5717090/double-checked-locking-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!