Double checked locking in Android
Asked Answered
C

2

20

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?

Capitalization answered 19/4, 2011 at 13:26 Comment(1)
You can probably guess at which I was looking at ;)Yellow
I
9

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

Impuissant answered 19/4, 2011 at 14:27 Comment(4)
Yup. With the addition of the "volatile" keyword, this will work on uniprocessor (all versions of Android) and SMP (3.0 "honeycomb" and later).Lingerfelt
Otherwise, before honeycomb, is double lock checking with non volatile fields possible ? @Fadden BTW, is there any reflection calls caching in the dalvik java.lang.Class class ? By caching I mean there is some bytecode generation like on the java VM : https://mcmap.net/q/76398/-any-way-to-further-optimize-java-reflective-method-invocationYellow
You need to use some sort of synchronization operation (volatile, synchronized, etc.) as shown on Pugh's site. The broken example in the question is, well, broken, and should not be used. The implementation of reflection in Dalvik has changed a fair bit over time, so you'd have to look at the code for a given release to know exactly what it does. I believe there is some caching, but to the best of my knowledge bytecode generation is not one of the techniques used.Lingerfelt
@DanieleSegato I believe this answers the question you had on the other answer. I have no direct knowledge of Art's behavior, but there's no reason to believe it wouldn't handle this correctly.Lingerfelt
Y
0

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.

Yellow answered 19/2, 2014 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.