Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 437
emmby Avatar asked Apr 19 '11 13:04

emmby


1 Answers

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

like image 168
sbridges Avatar answered Oct 13 '22 17:10

sbridges