Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, you should absolutely synchronize (or use a better idiom like the <a href="http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom" rel="nofollow"><em>Singleton Holder idiom</em></a>). Otherwise you run the risk of multiple threads initializing your object multiple times (and then subsequently using different instances).</p> <p>Consider a sequence of events like this:</p> <ol> <li>Thread A enters <code>getMyObj()</code> and sees that <code>obj == null</code></li> <li>Thread B enters <code>getMyObj()</code> and sees that <code>obj == null</code></li> <li>Thread A constructs a <code>new MyObj()</code> - let's call it <code>objA</code></li> <li>Thread B constructs a <code>new MyObj()</code> - let's call it <code>objB</code></li> <li>Thread A assigns <code>objA</code> to <code>obj</code></li> <li>Thread B assigns <code>objB</code> to <code>obj</code> (which is not <code>null</code> anymore at this point, so the reference to <code>objA</code>, assigned by Thread A, is overwritten)</li> <li>Thread A exits <code>getMyObj()</code> and starts to use <code>objA</code></li> <li>Thread B exits <code>getMyObj()</code> and starts to use <code>objB</code></li> </ol> <p>This scenario can happen with any number of threads. Note that although here, for the sake of simplicity, I assumed a strict ordering of events, in a real multithreaded environment events 1-2, 3-4 and/or 7-8 can partly or fully overlap in time, without changing the end result.</p> <p>An example to the holder idiom:</p> <pre><code>public class Something { private Something() { } private static class LazyHolder { public static final Something INSTANCE = new Something(); } public static Something getInstance() { return LazyHolder.INSTANCE; } } </code></pre> <p>This is guaranteed to be safe, as <code>INSTANCE</code> is <code>final</code>. The Java memory model guarantees that <code>final</code> fields are initialized and made visible correctly to any number of threads, upon loading the containing class. Since <code>LazyHolder</code> is <code>private</code> and is referenced only by <code>getInstance()</code>, it will only get loaded when <code>getInstance()</code> is first called. And at that point, <code>INSTANCE</code> is initialized in the background and published safely by the JVM.</p>
 

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