简体   繁体   中英

Why DCl without volatile is valid for primitives?

Discalimer: I don't use DCl in real production code - I have an academic interest only.

I've read following famous article: The "Double-Checked Locking is Broken" Declaration

The problem declaration(my vision):

// Correct multithreaded version
class Foo { 
  private Helper helper = null;
  public synchronized Helper getHelper() {
    if (helper == null) 
        helper = new Helper();
    return helper;
    }
  // other functions and members...
  }

Let's imagine that thread_1 executed line helper = new Helper(); Another Thread( thread_2 ) might see that helper link is not null but it is not initialized yet. It happens because of constructor invocation might be reordered with helper link assignment from thread_2 veiw.

But at this article mentioned that this approcach works properly for 32 bit primitives.

Although the double-checked locking idiom cannot be used for references to objects, it can work for 32-bit primitive values (eg, int's or float's). Note that it does not work for long's or double's, since unsynchronized reads/writes of 64-bit primitives are not guaranteed to be atomic.

// Correct Double-Checked Locking for 32-bit primitives
class Foo { 
  private int cachedHashCode = 0;
  public int hashCode() {
    int h = cachedHashCode;
    if (h == 0) 
    synchronized(this) {
      if (cachedHashCode != 0) return cachedHashCode;
      h = computeHashCode();
      cachedHashCode = h;
      }
    return h;
    }
  // other functions and members...
  }

Please explain me why it works? I know that 32 bit write is atomic.

What the reason of local variable here?

The essence of the "DCL is broken" trope is that, using DCL to initialize a singleton object, a thread could see the reference to the object before it sees the object in a fully initialized state. DCL adequately synchronizes the effectively final global variable that refers to the singleton, but it fails to synchronize the singleton object to which the global refers.

In your example, there's only just the global variable. There is no "object to which it refers."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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