<p>I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night.  This is a temporary solution until I can diagnose the stoppage.</p>

<p>I created a task to run under my admin user, and to start the program, <em>cmd</em> with the arguments <em>/c net start mssqlserver</em>.  When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:</p>

<p><em>action "C:\Windows\system32\cmd.EXE" with return code 2</em>.</p>

<p>Any suggestions?</p>

[{'answer_id': 70737, 'author': 'Neil Burroughs', 'author_id': 5166, 'author_profile': 'https://Stackoverflow.com/users/5166', 'pm_score': 6, 'selected': False, 'text': '<p>Make sure that you really need it. Do a google search for &quot;singleton anti-pattern&quot; to see some arguments against it.</p>\n<p>There\'s nothing inherently wrong with it I suppose, but it\'s just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I\'ve found <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.</p>\n'}, {'answer_id': 70749, 'author': 'macbirdie', 'author_id': 5049, 'author_profile': 'https://Stackoverflow.com/users/5049', 'pm_score': 4, 'selected': False, 'text': '<p>Wikipedia has some <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">examples</a> of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).</p>\n'}, {'answer_id': 70821, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.</p>\n<p>Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they\'re easy to understand by everybody. They\'re used as a mechanism for getting &quot;global&quot; data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like <a href="https://en.wikipedia.org/wiki/Inversion_of_control" rel="nofollow noreferrer">inversion of control</a> (IoC) or <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) for a nice middle ground.</p>\n<p>If you really need one then Wikipedia has a good example of a proper implementation of a singleton.</p>\n'}, {'answer_id': 70824, 'author': 'Jonathan', 'author_id': 1772, 'author_profile': 'https://Stackoverflow.com/users/1772', 'pm_score': 7, 'selected': False, 'text': '<p>Forget <a href="https://en.wikipedia.org/wiki/Lazy_initialization" rel="nofollow noreferrer">lazy initialization</a>; it\'s too problematic. This is the simplest solution:</p>\n<pre><code>public class A {    \n\n    private static final A INSTANCE = new A();\n\n    private A() {}\n\n    public static A getInstance() {\n        return INSTANCE;\n    }\n}\n</code></pre>\n'}, {'answer_id': 70829, 'author': 'Aleksi Yrttiaho', 'author_id': 11427, 'author_profile': 'https://Stackoverflow.com/users/11427', 'pm_score': 4, 'selected': False, 'text': "<p>If you do not need lazy loading then simply try:</p>\n<pre><code>public class Singleton {\n    private final static Singleton INSTANCE = new Singleton();\n\n    private Singleton() {}\n\n    public static Singleton getInstance() { return Singleton.INSTANCE; }\n\n    protected Object clone() {\n        throw new CloneNotSupportedException();\n    }\n}\n</code></pre>\n<p>If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:</p>\n<pre><code>public class Singleton {\n    private static Singleton instance = null;\n\n    private Singleton() {}\n\n    public static Singleton getInstance() {\n        if(null == instance) {\n            synchronized(Singleton.class) {\n                if(null == instance) {\n                    instance = new Singleton();\n                }\n            }\n        }\n        return instance;\n    }\n\n    protected Object clone() {\n        throw new CloneNotSupportedException();\n    }\n}\n</code></pre>\n<p>As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.</p>\n"}, {'answer_id': 70835, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 7, 'selected': False, 'text': "<p>Thread safe in Java 5+:</p>\n<pre><code>class Foo {\n    private static volatile Bar bar = null;\n    public static Bar getBar() {\n        if (bar == null) {\n            synchronized(Foo.class) {\n                if (bar == null)\n                    bar = new Bar();\n            }\n        }\n        return bar;\n    }\n}\n</code></pre>\n<hr />\n<p>Pay attention to the <code>volatile</code> modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value.  The synchronization <em>does not</em> take care of that--it only serializes access to that block of code.</p>\n<p>@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better.  Go read and vote up his answer too.</p>\n"}, {'answer_id': 71399, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': 11, 'selected': True, 'text': '<p>Use an enum:</p>\n\n<pre><code>public enum Foo {\n    INSTANCE;\n}\n</code></pre>\n\n<p>Joshua Bloch explained this approach in his <a href="http://sites.google.com/site/io/effective-java-reloaded" rel="noreferrer">Effective Java Reloaded</a> talk at Google I/O 2008: <a href="http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s" rel="noreferrer">link to video</a>. Also see slides 30-32 of his presentation (<a href="https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&amp;attredirects=0" rel="noreferrer">effective_java_reloaded.pdf</a>):</p>\n\n<blockquote>\n  <h3>The Right Way to Implement a Serializable Singleton</h3>\n\n<pre><code>public enum Elvis {\n    INSTANCE;\n    private final String[] favoriteSongs =\n        { "Hound Dog", "Heartbreak Hotel" };\n    public void printFavorites() {\n        System.out.println(Arrays.toString(favoriteSongs));\n    }\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Edit:</strong> An <a href="http://www.ddj.com/java/208403883?pgno=3" rel="noreferrer">online portion of "Effective Java"</a> says: </p>\n\n<blockquote>\n  <p>"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>."</p>\n</blockquote>\n'}, {'answer_id': 71574, 'author': 'Andrew Swan', 'author_id': 10433, 'author_profile': 'https://Stackoverflow.com/users/10433', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m mystified by some of the answers that suggest <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can\'t speak for other DI frameworks.</p>\n<p>So my answer to the OP would be (in all but the most trivial sample code) to:</p>\n<ol>\n<li>Use a DI framework like <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a>, then</li>\n<li>Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.</li>\n</ol>\n<p>This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).</p>\n'}, {'answer_id': 71683, 'author': 'Benno Richters', 'author_id': 3565, 'author_profile': 'https://Stackoverflow.com/users/3565', 'pm_score': 7, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/70835#70835">The solution posted by Stu Thompson</a> is valid in Java\xa05.0 and later. But I would prefer not to use it because I think it is error prone.</p>\n<p>It\'s easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of <a href="http://jcip.net/" rel="nofollow noreferrer" title="Java Concurrency in Practice">Java Concurrency in Practice</a>. In short: This pattern (prior to Java\xa05.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.</p>\n<p>This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.</p>\n<pre><code>class Bar {\n    private static class BarHolder {\n        public static Bar bar = new Bar();\n    }\n\n    public static Bar getBar() {\n        return BarHolder.bar;\n    }\n}\n</code></pre>\n'}, {'answer_id': 73763, 'author': 'Roel Spilker', 'author_id': 12634, 'author_profile': 'https://Stackoverflow.com/users/12634', 'pm_score': 8, 'selected': False, 'text': "<p>Depending on the usage, there are several &quot;correct&quot; answers.</p>\n<p>Since Java 5, the best way to do it is to use an enum:</p>\n<pre><code>public enum Foo {\n   INSTANCE;\n}\n</code></pre>\n<p>Pre Java 5, the most simple case is:</p>\n<pre><code>public final class Foo {\n\n    private static final Foo INSTANCE = new Foo();\n\n    private Foo() {\n        if (INSTANCE != null) {\n            throw new IllegalStateException(&quot;Already instantiated&quot;);\n        }\n    }\n\n    public static Foo getInstance() {\n        return INSTANCE;\n    }\n\n    public Object clone() throws CloneNotSupportedException{\n        throw new CloneNotSupportedException(&quot;Cannot clone instance of this class&quot;);\n    }\n}\n</code></pre>\n<p>Let's go over the code. First, you want the class to be final. In this case, I've used the <code>final</code> keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a <code>private static final Foo</code> field to hold the only instance, and a <code>public static Foo getInstance()</code> method to return it. The Java specification makes sure that the constructor is only called when the class is first used.</p>\n<p>When you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.</p>\n<p>You can use a <code>private static class</code> to load the instance. The code would then look like:</p>\n<pre><code>public final class Foo {\n\n    private static class FooLoader {\n        private static final Foo INSTANCE = new Foo();\n    }\n\n    private Foo() {\n        if (FooLoader.INSTANCE != null) {\n            throw new IllegalStateException(&quot;Already instantiated&quot;);\n        }\n    }\n\n    public static Foo getInstance() {\n        return FooLoader.INSTANCE;\n    }\n}\n</code></pre>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>\n<p>When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.</p>\n<pre><code>public final class Foo implements Serializable {\n\n    private static final long serialVersionUID = 1L;\n\n    private static class FooLoader {\n        private static final Foo INSTANCE = new Foo();\n    }\n\n    private Foo() {\n        if (FooLoader.INSTANCE != null) {\n            throw new IllegalStateException(&quot;Already instantiated&quot;);\n        }\n    }\n\n    public static Foo getInstance() {\n        return FooLoader.INSTANCE;\n    }\n\n    @SuppressWarnings(&quot;unused&quot;)\n    private Foo readResolve() {\n        return FooLoader.INSTANCE;\n    }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.</p>\n"}, {'answer_id': 74905, 'author': 'Georgi', 'author_id': 13209, 'author_profile': 'https://Stackoverflow.com/users/13209', 'pm_score': -1, 'selected': False, 'text': '<p>Sometimes a simple "<strong><code>static Foo foo = new Foo();</code></strong>" is not enough. Just think of some basic data insertion you want to do.</p>\n\n<p>On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is</p>\n\n<pre><code>public class Singleton {\n\n    private static Singleton instance = null;\n\n    static {\n          instance = new Singleton();\n          // do some of your instantiation stuff here\n    }\n\n    private Singleton() {\n          if(instance!=null) {\n                  throw new ErrorYouWant("Singleton double-instantiation, should never happen!");\n          }\n    }\n\n    public static getSingleton() {\n          return instance;\n    }\n\n}\n</code></pre>\n\n<p>Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the <strong>static { }</strong> - block. that\'s the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.</p>\n'}, {'answer_id': 117516, 'author': 'Matt', 'author_id': 20630, 'author_profile': 'https://Stackoverflow.com/users/20630', 'pm_score': 4, 'selected': False, 'text': '<p>I use the <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a> to manage my singletons.</p>\n<p>It doesn\'t enforce the &quot;singleton-ness&quot; of the class (which you can\'t really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.</p>\n'}, {'answer_id': 6918352, 'author': 'Onur', 'author_id': 776658, 'author_profile': 'https://Stackoverflow.com/users/776658', 'pm_score': 2, 'selected': False, 'text': '<p>You need the <a href="http://en.wikipedia.org/wiki/Double-checked_locking" rel="nofollow noreferrer">double-checking</a> idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom" rel="nofollow noreferrer">initialization on demand holder</a> idiom.</p>\n<p>In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.</p>\n<pre><code>public static final INSTANCE == ....\nprivate Object readResolve() {\n  return INSTANCE; // Original singleton instance.\n} \n</code></pre>\n'}, {'answer_id': 14372745, 'author': 'NullPoiиteя', 'author_id': 1723893, 'author_profile': 'https://Stackoverflow.com/users/1723893', 'pm_score': 3, 'selected': False, 'text': '<p>I would say an enum singleton.</p>\n<p>Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity\'s sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.</p>\n<p>The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.</p>\n<pre><code>/**\n* Singleton pattern example using a Java Enum\n*/\npublic enum Singleton {\n    INSTANCE;\n    public void execute (String arg) {\n        // Perform operation here\n    }\n}\n</code></pre>\n<p>You can access it by <code>Singleton.INSTANCE</code>, and it is much easier than calling the <code>getInstance()</code> method on Singleton.</p>\n<blockquote>\n<p>1.12    Serialization of Enum Constants</p>\n<p>Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, <code>ObjectOutputStream</code> writes the value returned by the enum constant\'s name method. To deserialize an enum constant, <code>ObjectInputStream</code> reads the constant name from the stream; the deserialized constant is then obtained by calling the <code>java.lang.Enum.valueOf</code> method, passing the constant\'s enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.</p>\n<p>The process by which enum constants are serialized cannot be customized: any class-specific <code>writeObject</code>, <code>readObject</code>, <code>readObjectNoData</code>, <code>writeReplace</code>, and <code>readResolve</code> methods defined by enum types are ignored during serialization and deserialization. Similarly, any <code>serialPersistentFields</code> or <code>serialVersionUID</code> field declarations are also ignored--all enum types have a fixed <code>serialVersionUID</code> of <code>0L</code>. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.</p>\n<p><a href="http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum" rel="nofollow noreferrer">Quoted from Oracle documentation</a></p>\n</blockquote>\n<p>Another problem with conventional Singletons are that once you implement the <code>Serializable</code> interface, they no longer remain singleton because the <code>readObject()</code> method always return a new instance, like a constructor in Java. This can be avoided by using <code>readResolve()</code> and discarding the newly created instance by replacing with a singleton like below:</p>\n<pre><code> // readResolve to prevent another instance of Singleton\n private Object readResolve(){\n     return INSTANCE;\n }\n</code></pre>\n<p>This can become even more complex if your <em>singleton class</em> maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.</p>\n<hr />\n<p><strong>Good Read</strong></p>\n<ol>\n<li><a href="http://www.oodesign.com/singleton-pattern.html" rel="nofollow noreferrer">Singleton Pattern</a></li>\n<li><a href="https://stackoverflow.com/questions/13219678/enums-singletons-and-deserialization">Enums, Singletons and Deserialization</a></li>\n<li><a href="http://www.ibm.com/developerworks/java/library/j-dcl/index.html" rel="nofollow noreferrer">Double-checked locking and the Singleton pattern</a></li>\n</ol>\n'}, {'answer_id': 14917772, 'author': 'Abhijit Gaikwad', 'author_id': 403872, 'author_profile': 'https://Stackoverflow.com/users/403872', 'pm_score': 4, 'selected': False, 'text': "<p>Following are three different approaches</p>\n<ol>\n<li><p>Enum</p>\n<pre><code> /**\n * Singleton pattern example using Java Enum\n */\n public enum EasySingleton {\n     INSTANCE;\n }\n</code></pre>\n</li>\n<li><p>Double checked locking / lazy loading</p>\n<pre><code> /**\n * Singleton pattern example with Double checked Locking\n */\n public class DoubleCheckedLockingSingleton {\n      private static volatile DoubleCheckedLockingSingleton INSTANCE;\n\n      private DoubleCheckedLockingSingleton() {}\n\n      public static DoubleCheckedLockingSingleton getInstance() {\n          if(INSTANCE == null) {\n             synchronized(DoubleCheckedLockingSingleton.class) {\n                 // Double checking Singleton instance\n                 if(INSTANCE == null) {\n                     INSTANCE = new DoubleCheckedLockingSingleton();\n                 }\n             }\n          }\n          return INSTANCE;\n      }\n }\n</code></pre>\n</li>\n<li><p>Static factory method</p>\n<pre><code> /**\n * Singleton pattern example with static factory method\n */\n\n public class Singleton {\n     // Initialized during class loading\n     private static final Singleton INSTANCE = new Singleton();\n\n     // To prevent creating another instance of 'Singleton'\n     private Singleton() {}\n\n     public static Singleton getSingleton() {\n         return INSTANCE;\n     }\n }\n</code></pre>\n</li>\n</ol>\n"}, {'answer_id': 16580366, 'author': 'Ajinkya', 'author_id': 705773, 'author_profile': 'https://Stackoverflow.com/users/705773', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Disclaimer:</strong> I have just summarized all of the awesome answers and wrote it in my own words.</p>\n<hr />\n<p>While implementing Singleton we have two options:</p>\n<ol>\n<li>Lazy loading</li>\n<li>Early loading</li>\n</ol>\n<p>Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.</p>\n<p>The most simple way of implementing a singleton is:</p>\n<pre><code>public class Foo {\n\n    // It will be our sole hero\n    private static final Foo INSTANCE = new Foo();\n\n    private Foo() {\n        if (INSTANCE != null) {\n            // SHOUT\n            throw new IllegalStateException(&quot;Already instantiated&quot;);\n        }\n    }\n\n    public static Foo getInstance() {\n        return INSTANCE;\n    }\n}\n</code></pre>\n<p>Everything is good except it\'s an early loaded singleton. Lets try lazy loaded singleton</p>\n<pre><code>class Foo {\n\n    // Our now_null_but_going_to_be sole hero\n    private static Foo INSTANCE = null;\n\n    private Foo() {\n        if (INSTANCE != null) {\n            // SHOUT\n            throw new IllegalStateException(&quot;Already instantiated&quot;);\n        }\n    }\n\n    public static Foo getInstance() {\n        // Creating only  when required.\n        if (INSTANCE == null) {\n            INSTANCE = new Foo();\n        }\n        return INSTANCE;\n    }\n}\n</code></pre>\n<p>So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.\nSo let’s protect it from evil multi threading:</p>\n<pre><code>class Foo {\n\n    private static Foo INSTANCE = null;\n\n    // TODO Add private shouting constructor\n\n    public static Foo getInstance() {\n        // No more tension of threads\n        synchronized (Foo.class) {\n            if (INSTANCE == null) {\n                INSTANCE = new Foo();\n            }\n        }\n        return INSTANCE;\n    }\n}\n</code></pre>\n<p>But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:</p>\n<pre><code>class Foo {\n\n    // Pay attention to volatile\n    private static volatile Foo INSTANCE = null;\n\n    // TODO Add private shouting constructor\n\n    public static Foo getInstance() {\n        if (INSTANCE == null) { // Check 1\n            synchronized (Foo.class) {\n                if (INSTANCE == null) { // Check 2\n                    INSTANCE = new Foo();\n                }\n            }\n        }\n        return INSTANCE;\n    }\n}\n</code></pre>\n<p>This is called the &quot;double-checked locking idiom&quot;. It\'s easy to forget the volatile statement and difficult to understand why it is necessary.\nFor details: <em><a href="http://www.cs.umd.edu/%7Epugh/java/memoryModel/DoubleCheckedLocking.html" rel="noreferrer">The &quot;Double-Checked Locking is Broken&quot; Declaration</a></em></p>\n<p>Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:</p>\n<pre><code>class Foo implements Serializable {\n\n    private static final long serialVersionUID = 1L;\n\n    private static volatile Foo INSTANCE = null;\n\n    // The rest of the things are same as above\n\n    // No more fear of serialization\n    @SuppressWarnings(&quot;unused&quot;)\n    private Object readResolve() {\n        return INSTANCE;\n    }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.</p>\n<p>Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:</p>\n<pre><code>public final class Foo implements Serializable {\n\n    private static final long serialVersionUID = 1L;\n\n    // Wrapped in a inner static class so that loaded only when required\n    private static class FooLoader {\n\n        // And no more fear of threads\n        private static final Foo INSTANCE = new Foo();\n    }\n\n    // TODO add private shouting construcor\n\n    public static Foo getInstance() {\n        return FooLoader.INSTANCE;\n    }\n\n    // Damn you serialization\n    @SuppressWarnings(&quot;unused&quot;)\n    private Foo readResolve() {\n        return FooLoader.INSTANCE;\n    }\n}\n</code></pre>\n<p>Yes, this is our very same hero :)</p>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class <code>FooLoader</code> is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.</p>\n<p>And we have come so far. Here is the best way to achieve everything we did is best possible way:</p>\n<pre><code>public enum Foo {\n    INSTANCE;\n}\n</code></pre>\n<p>Which internally will be treated like</p>\n<pre><code>public class Foo {\n\n    // It will be our sole hero\n    private static final Foo INSTANCE = new Foo();\n}\n</code></pre>\n<p>That\'s it! No more fear of serialization, threads and ugly code. Also <a href="https://stackoverflow.com/questions/16771373/singleton-via-enum-way-is-lazy-initialized"><strong>ENUMS singleton are lazily initialized</strong></a>.</p>\n<blockquote>\n<p>This approach is functionally equivalent to the public field approach,\nexcept that it is more concise, provides the serialization machinery\nfor free, and provides an  ironclad guarantee against multiple\ninstantiation, even in the face of sophisticated serialization or\nreflection attacks. While this approach has yet to be widely  adopted,\na single-element enum type is the best way to implement a singleton.</p>\n</blockquote>\n<p>-Joshua Bloch in &quot;Effective Java&quot;</p>\n<p>Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)</p>\n<p>Updated it on my <a href="http://ajinkyaparakh.blogspot.in/2013/05/implementing-singleton-in-java.html" rel="noreferrer"><strong>blog</strong></a>.</p>\n'}, {'answer_id': 16699497, 'author': 'raoadnan', 'author_id': 2392052, 'author_profile': 'https://Stackoverflow.com/users/2392052', 'pm_score': 2, 'selected': False, 'text': '<p>For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).</p>\n'}, {'answer_id': 19562324, 'author': 'rohan kamat', 'author_id': 2335562, 'author_profile': 'https://Stackoverflow.com/users/2335562', 'pm_score': 1, 'selected': False, 'text': '<p>Simplest singleton class:</p>\n<pre><code>public class Singleton {\n  private static Singleton singleInstance = new Singleton();\n  private Singleton() {}\n  public static Singleton getSingleInstance() {\n    return singleInstance;\n  }\n}\n</code></pre>\n'}, {'answer_id': 19849576, 'author': 'somenath mukhopadhyay', 'author_id': 873952, 'author_profile': 'https://Stackoverflow.com/users/873952', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public class Singleton {\n\n    private static final Singleton INSTANCE = new Singleton();\n\n    private Singleton() {\n        if (INSTANCE != null)\n            throw new IllegalStateException(“Already instantiated...”);\n        }\n\n\n    public synchronized static Singleton getInstance() {\n        return INSTANCE;\n    }\n\n}\n</code></pre>\n<p>As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.</p>\n'}, {'answer_id': 27793921, 'author': 'shikjohari', 'author_id': 2595642, 'author_profile': 'https://Stackoverflow.com/users/2595642', 'pm_score': 0, 'selected': False, 'text': '<p>I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.</p>\n<pre><code>public enum Singleton {\n    INSTANCE;\n}\n</code></pre>\n<p>And you are done!</p>\n'}, {'answer_id': 29389322, 'author': 'coderz', 'author_id': 3275167, 'author_profile': 'https://Stackoverflow.com/users/3275167', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Version 1:</strong></p>\n\n<pre><code>public class MySingleton {\n    private static MySingleton instance = null;\n    private MySingleton() {}\n    public static synchronized MySingleton getInstance() {\n        if(instance == null) {\n            instance = new MySingleton();\n        }\n        return instance;\n    }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with blocking, low performance because of <code>synchronized</code>.</p>\n\n<p><strong>Version 2:</strong></p>\n\n<pre><code>public class MySingleton {\n    private MySingleton() {}\n    private static class MySingletonHolder {\n        public final static MySingleton instance = new MySingleton();\n    }\n    public static MySingleton getInstance() {\n        return MySingletonHolder.instance;\n    }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with non-blocking, high performance.</p>\n'}, {'answer_id': 32130663, 'author': 'kenju', 'author_id': 2775013, 'author_profile': 'https://Stackoverflow.com/users/2775013', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at this post.</p>\n<p><a href="https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries">Examples of GoF Design Patterns in Java&#39;s core libraries</a></p>\n<p>From the best answer\'s &quot;Singleton&quot; section,</p>\n<blockquote>\n<h3>Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)</h3>\n<ul>\n<li>java.lang.Runtime#getRuntime()</li>\n<li>java.awt.Desktop#getDesktop()</li>\n<li>java.lang.System#getSecurityManager()</li>\n</ul>\n</blockquote>\n<p>You can also learn the example of Singleton from Java native classes themselves.</p>\n'}, {'answer_id': 32286179, 'author': 'Shailendra Singh', 'author_id': 2550410, 'author_profile': 'https://Stackoverflow.com/users/2550410', 'pm_score': 2, 'selected': False, 'text': '<p>Various ways to make a singleton object:</p>\n<ol>\n<li><p>As per <a href="https://en.wikipedia.org/wiki/Joshua_Bloch" rel="nofollow noreferrer">Joshua Bloch</a> - Enum would be the best.</p>\n</li>\n<li><p>You can use double check locking also.</p>\n</li>\n<li><p>Even an inner static class can be used.</p>\n</li>\n</ol>\n'}, {'answer_id': 32906229, 'author': 'Dan Moldovan', 'author_id': 2725534, 'author_profile': 'https://Stackoverflow.com/users/2725534', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Enum singleton</strong></p>\n<p>The simplest way to implement a singleton that is thread-safe is using an Enum:</p>\n<pre><code>public enum SingletonEnum {\n  INSTANCE;\n  public void doSomething(){\n    System.out.println(&quot;This is a singleton&quot;);\n  }\n}\n</code></pre>\n<p>This code works since the introduction of Enum in Java 1.5</p>\n<p><strong>Double checked locking</strong></p>\n<p>If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.</p>\n<pre><code>public class Singleton {\n\n  private static volatile Singleton instance = null;\n\n  private Singleton() {\n  }\n\n  public static Singleton getInstance() {\n    if (instance == null) {\n      synchronized (Singleton.class){\n        if (instance == null) {\n          instance = new Singleton();\n        }\n      }\n    }\n    return instance;\n  }\n}\n</code></pre>\n<p>This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.</p>\n<p><strong>Early loading singleton (works even before Java 1.5)</strong></p>\n<p>This implementation instantiates the singleton when the class is loaded and provides thread safety.</p>\n<pre><code>public class Singleton {\n\n  private static final Singleton instance = new Singleton();\n\n  private Singleton() {\n  }\n\n  public static Singleton getInstance() {\n    return instance;\n  }\n\n  public void doSomething(){\n    System.out.println(&quot;This is a singleton&quot;);\n  }\n\n}\n</code></pre>\n'}, {'answer_id': 37305099, 'author': 'Nicolas Filotto', 'author_id': 1997376, 'author_profile': 'https://Stackoverflow.com/users/1997376', 'pm_score': 2, 'selected': False, 'text': '<p>This is how to implement a simple <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a>:</p>\n<pre><code>public class Singleton {\n    // It must be static and final to prevent later modification\n    private static final Singleton INSTANCE = new Singleton();\n    /** The constructor must be private to prevent external instantiation */\n    private Singleton(){}\n    /** The public static method allowing to get the instance */\n    public static Singleton getInstance() {\n        return INSTANCE;\n    }\n}\n</code></pre>\n<p>This is how to properly lazy create your singleton:</p>\n<pre><code>public class Singleton {\n    // The constructor must be private to prevent external instantiation\n    private Singleton(){}\n    /** The public static method allowing to get the instance */\n    public static Singleton getInstance() {\n        return SingletonHolder.INSTANCE;\n    }\n    /**\n     * The static inner class responsible for creating your instance only on demand,\n     * because the static fields of a class are only initialized when the class\n     * is explicitly called and a class initialization is synchronized such that only\n     * one thread can perform it, this rule is also applicable to inner static class\n     * So here INSTANCE will be created only when SingletonHolder.INSTANCE\n     * will be called\n     */\n    private static class SingletonHolder {\n        private static final Singleton INSTANCE = new Singleton();\n    }\n}\n</code></pre>\n'}, {'answer_id': 38942086, 'author': 'user3792852', 'author_id': 3792852, 'author_profile': 'https://Stackoverflow.com/users/3792852', 'pm_score': 2, 'selected': False, 'text': '<p>Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:</p>\n<pre><code>public class SingletonImpl {\n\n    private static SingletonImpl instance;\n\n    public static SingletonImpl getInstance() {\n        if (instance == null) {\n            instance = new SingletonImpl();\n        }\n        return instance;\n    }\n\n    public static void setInstance(SingletonImpl impl) {\n        instance = impl;\n    }\n\n    public void a() {\n        System.out.println(&quot;Default Method&quot;);\n    }\n}\n</code></pre>\n<p>The added <code>setInstance</code> method allows setting a mockup implementation of the singleton class during testing:</p>\n<pre><code>public class SingletonMock extends SingletonImpl {\n\n    @Override\n    public void a() {\n        System.out.println(&quot;Mock Method&quot;);\n    }\n\n}\n</code></pre>\n<p>This also works with early initialization approaches:</p>\n<pre><code>public class SingletonImpl {\n\n    private static final SingletonImpl instance = new SingletonImpl();\n\n    private static SingletonImpl alt;\n\n    public static void setInstance(SingletonImpl inst) {\n        alt = inst;\n    }\n\n    public static SingletonImpl getInstance() {\n        if (alt != null) {\n            return alt;\n        }\n        return instance;\n    }\n\n    public void a() {\n        System.out.println(&quot;Default Method&quot;);\n    }\n}\n\npublic class SingletonMock extends SingletonImpl {\n\n    @Override\n    public void a() {\n        System.out.println(&quot;Mock Method&quot;);\n    }\n\n}\n</code></pre>\n<p>This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.</p>\n<p>Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.</p>\n'}, {'answer_id': 39098595, 'author': 'Dheeraj Sachan', 'author_id': 3314058, 'author_profile': 'https://Stackoverflow.com/users/3314058', 'pm_score': 3, 'selected': False, 'text': '<p>There are four ways to create a singleton in Java.</p>\n<ol>\n<li><p>Eager initialization singleton</p>\n<pre><code> public class Test {\n     private static final Test test = new Test();\n\n     private Test() {\n     }\n\n     public static Test getTest() {\n         return test;\n     }\n }\n</code></pre>\n</li>\n<li><p>Lazy initialization singleton (thread safe)</p>\n<pre><code> public class Test {\n      private static volatile Test test;\n\n      private Test() {\n      }\n\n      public static Test getTest() {\n         if(test == null) {\n             synchronized(Test.class) {\n                 if(test == null) {\n                     test = new Test();\n                 }\n             }\n         }\n         return test;\n     }\n }\n</code></pre>\n</li>\n<li><p>Bill Pugh singleton with holder pattern (preferably the best one)</p>\n<pre><code> public class Test {\n\n     private Test() {\n     }\n\n     private static class TestHolder {\n         private static final Test test = new Test();\n     }\n\n     public static Test getInstance() {\n         return TestHolder.test;\n     }\n }\n</code></pre>\n</li>\n<li><p>Enum singleton</p>\n<pre><code> public enum MySingleton {\n     INSTANCE;\n\n     private MySingleton() {\n         System.out.println(&quot;Here&quot;);\n     }\n }\n</code></pre>\n</li>\n</ol>\n'}, {'answer_id': 45062746, 'author': 'Michael Andrews', 'author_id': 1829927, 'author_profile': 'https://Stackoverflow.com/users/1829927', 'pm_score': 4, 'selected': False, 'text': '<p>There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let\'s start at the beginning and iterate on the problem. You\'ll see what I mean.</p>\n<hr />\n<p>The first attempt might look something like this:</p>\n<pre><code>public class MySingleton {\n\n     private static MySingleton INSTANCE;\n\n     public static MySingleton getInstance() {\n        if (INSTANCE == null) {\n            INSTANCE = new MySingleton();\n        }\n        return INSTANCE;\n    }\n    ...\n}\n</code></pre>\n<p>Here we have the MySingleton class which has a private static member called <em>INSTANCE</em>, and a public static method called getInstance(). The first time getInstance() is called, the <em>INSTANCE</em> member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the <em>INSTANCE</em> variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().</p>\n<p>But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the <em>INSTANCE</em> member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the <em>INSTANCE</em> member.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static synchronized MySingleton getInstance() {\n    if (INSTANCE == null) {\n        INSTANCE = new MySingleton();\n    }\n    return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of <em>INSTANCE</em>. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n    if (INSTANCE == null) {\n        synchronize(MySingleton.class) {\n            INSTANCE = new MySingleton();\n        }\n    }\n    return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the <em>INSTANCE</em> member as null.</p>\n<p>They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n    if (INSTANCE == null) {\n        synchronized(MySingleton.class) {\n            if (INSTANCE == null) {\n                INSTANCE = createInstance();\n            }\n        }\n    }\n    return INSTANCE;\n}\n</code></pre>\n<p>Here we issue another check from <em>inside</em> the block. If the <em>INSTANCE</em> member has already been set, we’ll skip initialization. This is called double-checked locking.</p>\n<p>This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the <em>INSTANCE</em> member has been updated. This is because of how Java optimizes memory operations.</p>\n<p>Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread\u200a—\u200abeing processed by a different CPU or core, using a different cache\u200a—\u200awill not see the changes made by the first. This will cause the second thread to see the <em>INSTANCE</em> member as null forcing a new instance of our singleton to be created.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n    if (INSTANCE == null) {\n        synchronized(MySingleton.class) {\n            if (INSTANCE == null) {\n                INSTANCE = createInstance();\n            }\n        }\n    }\n    return INSTANCE;\n}\n</code></pre>\n<p>We solve this by using the <em>volatile</em> keyword on the declaration of the <em>INSTANCE</em> member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.</p>\n<p>But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile <em>INSTANCE</em> member\u200a—\u200awhich we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n    MySingleton result = INSTANCE;\n    if (result == null) {\n        synchronized(MySingleton.class) {\n            result = INSTANCE;\n            if (result == null) {\n                INSTANCE = result = createInstance();\n            }\n        }\n    }\n    return result;\n}\n</code></pre>\n<p>Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.</p>\n<p>I wrote an article about this recently. <a href="https://medium.com/@michael.andrews/deconstructing-the-singleton-b5f881f85f5" rel="noreferrer">Deconstructing The Singleton</a>. You can find more information on these examples and an example of the &quot;holder&quot; pattern there. There is also a real-world example showcasing the double-checked volatile approach.</p>\n'}, {'answer_id': 52265460, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>The best singleton pattern I've ever seen uses the Supplier interface.</p>\n\n<ul>\n<li>It's generic and reusable</li>\n<li>It supports lazy initialization</li>\n<li>It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.</li>\n</ul>\n\n<p>See below:</p>\n\n<pre><code>public class Singleton&lt;T&gt; implements Supplier&lt;T&gt; {\n\n    private boolean initialized;\n    private Supplier&lt;T&gt; singletonSupplier;\n\n    public Singleton(T singletonValue) {\n        this.singletonSupplier = () -&gt; singletonValue;\n    }\n\n    public Singleton(Supplier&lt;T&gt; supplier) {\n        this.singletonSupplier = () -&gt; {\n            // The initial supplier is temporary; it will be replaced after initialization\n            synchronized (supplier) {\n                if (!initialized) {\n                    T singletonValue = supplier.get();\n                    // Now that the singleton value has been initialized,\n                    // replace the blocking supplier with a non-blocking supplier\n                    singletonSupplier = () -&gt; singletonValue;\n                    initialized = true;\n                }\n                return singletonSupplier.get();\n            }\n        };\n    }\n\n    @Override\n    public T get() {\n        return singletonSupplier.get();\n    }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/70694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8741/']