Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Without <code>volatile</code> the code doesn't work correctly with multiple threads.</p> <p>From Wikipedia's <a href="http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java" rel="noreferrer">Double-checked locking</a>:</p> <blockquote> <p>As of J2SE 5.0, this problem has been fixed. The volatile keyword now ensures that multiple threads handle the singleton instance correctly. This new idiom is described in <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html" rel="noreferrer">The "Double-Checked Locking is Broken" Declaration</a>:</p> </blockquote> <pre><code>// Works with acquire/release semantics for volatile // Broken under Java 1.4 and earlier semantics for volatile class Foo { private volatile Helper helper = null; public Helper getHelper() { Helper result = helper; if (result == null) { synchronized(this) { result = helper; if (result == null) { helper = result = new Helper(); } } } return result; } // other functions and members... } </code></pre> <p>In general you should avoid double-check locking if possible, as it is difficult to get right and if you get it wrong it can be difficult to find the error. Try this simpler approach instead:</p> <blockquote> <p>If the helper object is static (one per class loader), an alternative is the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom" rel="noreferrer">initialization on demand holder idiom</a></p> </blockquote> <pre><code>// Correct lazy initialization in Java @ThreadSafe class Foo { private static class HelperHolder { public static Helper helper = new Helper(); } public static Helper getHelper() { return HelperHolder.helper; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload