Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are implementing the <a href="http://en.wikipedia.org/wiki/Lazy_initialization" rel="noreferrer"><em>lazy initialization</em></a> pattern - where the instance is created when first used.</p> <p>But there is a simple trick that allows you to code a threadsafe implementation that <em>doesn't</em> require synchronization! It is known as the <a href="http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom" rel="noreferrer"><em>Initialization-on-demand holder idiom</em></a>, and it looks like this:</p> <pre><code>public class CassandraAstyanaxConnection { private CassandraAstyanaxConnection(){ } private static class Holder { private static final CassandraAstyanaxConnection INSTANCE = new CassandraAstyanaxConnection(); } public static CassandraAstyanaxConnection getInstance() { return Holder.INSTANCE; } // rest of class omitted } </code></pre> <p>This code initializes the instance on the first calling of <code>getInstance()</code>, and importantly doesn't need synchronization because of the contract of the class loader:</p> <ul> <li>the class loader loads classes when they are first accessed (in this case <code>Holder</code>'s only access is within the <code>getInstance()</code> method)</li> <li>when a class is loaded, and before anyone can use it, all static initializers are guaranteed to be executed (that's when <code>Holder</code>'s static block fires)</li> <li>the class loader has its own synchronization built right in that make the above two points guaranteed to be threadsafe</li> </ul> <p>It's a neat little trick that I use whenever I need lazy initialization. You also get the bonus of a <code>final</code> instance, even though it's created lazily. Also note how clean and simple the code is.</p> <p><strong>Edit:</strong> You should set all constructors as private or protected. Setting and empty private constructor will do the work</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