{"id":2124,"date":"2017-04-04T16:47:43","date_gmt":"2017-04-04T16:47:43","guid":{"rendered":"http:\/\/codethataint.com\/blog\/?p=2124"},"modified":"2024-11-07T10:28:01","modified_gmt":"2024-11-07T10:28:01","slug":"different-implementation-of-singleton-pattern","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/different-implementation-of-singleton-pattern\/","title":{"rendered":"Different Implementation of Singleton Pattern"},"content":{"rendered":"<p><strong>When Singleton should be used?<\/strong><br \/>\nSingleton should be used incase creation of Object is costly or heavy I.E. DBConnection. It should not be used if the Object is mutable.<\/p>\n<ol>\n<li>Eager initialization<\/li>\n<li>Lazy initialization<\/li>\n<li>Static block initialization<\/li>\n<li>Using Synchronized method<\/li>\n<li>Using Synchronized block<\/li>\n<li>Double Checked Locking<\/li>\n<li>Enum Singleton<\/li>\n<li>Initialization on demand holder idiom<\/li>\n<\/ol>\n<p>3 Things are common across all singleton implementation<\/p>\n<blockquote><p>\nprivate constructor<br \/>\npublic static getInstance Method<br \/>\nprivate static instance field\n<\/p><\/blockquote>\n<p><strong  class=\"ctaHeader3\">Eager initialization<\/strong><br \/>\nAn instance of Singleton Class is created at the time of class loading<\/p>\n<p><strong>EagerInitialized.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.singleton;\r\n\r\npublic class EagerInitialized {\r\n\t\r\n\tprivate static final EagerInitialized instance = new EagerInitialized();\r\n\t\r\n\t\/\/Private Constructor\r\n\tprivate EagerInitialized()\r\n\t{\r\n\t}\r\n\t\r\n\tpublic static EagerInitialized getInstance()\r\n\t{\r\n         return instance;\r\n        }\t\r\n}\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">Lazy Initialization<\/strong><br \/>\nWith lazy initialization you crate instance only when its needed and not when the class is loaded<\/p>\n<p><strong>LazyInitialized.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.singleton;\r\n\r\npublic class LazyInitialized \r\n{\r\n\tpublic static  LazyInitialized instance = null; \r\n\t\r\n\tprivate LazyInitialized()\r\n\t{\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic static LazyInitialized getInstance(){\r\n        if(instance == null){\r\n            instance = new LazyInitialized();\r\n        }\r\n        return instance;\r\n    }\r\n}\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">Static Block Initialization<\/strong><br \/>\nStatic block initialization is similar to eager initialization, except that an instance of class is created in the static block that provides an option for exception handling.<\/p>\n<p><strong>StaticBlockInitialized.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.singleton;\r\n\r\npublic class StaticBlockInitialized {\r\n\r\n\tprivate static StaticBlockInitialized instance;\r\n\r\n\tprivate StaticBlockInitialized() {\r\n\t}\r\n\r\n\t\/\/ Static block initialization for exception handling\r\n\tstatic {\r\n\t\ttry {\r\n\t\t\tinstance = new StaticBlockInitialized();\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RuntimeException(&quot;Exception occurred in creating singleton instance&quot;);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static StaticBlockInitialized getInstance() {\r\n\t\treturn instance;\r\n\t}\r\n}\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\">Using Synchronized Method<\/strong><br \/>\nThe easier way to create a thread-safe singleton class is to make the access method synchronized, so that only one thread can execute this method at a time.<\/p>\n<p><strong>ThreadSafeSing.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.singleton;\r\n\r\npublic class ThreadSafeSing {\r\n\r\n    private static ThreadSafeSinginstance;\r\n    \r\n    private ThreadSafeSing(){}\r\n    \r\n    public static synchronized ThreadSafeSing getInstance(){\r\n        if(instance == null){\r\n            instance = new ThreadSafeSing();\r\n        }\r\n        return instance;\r\n    }    \r\n}\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\">Using Synchronized Block<\/strong><br \/>\nThe easier way to create a thread-safe singleton class is to make the access method synchronized, so that only one thread can execute this method at a time. Refer the link for the same <a href=\"http:\/\/codethataint.com\/blog\/synchronized-block-vs-synchronized-method\/\">Link<\/a><\/p>\n<p><strong>ThreadSafeSing.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.singleton;\r\n\r\npublic class ThreadSafeSing {\r\n    private static ThreadSafeSinginstance;\r\n    \r\n    private ThreadSafeSing(){}\r\n    \r\n    public static ThreadSafeSing getInstance(){\r\n        Synchronized(ThreadSafeSing.class){ \r\n          if(instance == null){\r\n            instance = new ThreadSafeSing();\r\n          }\r\n        }\r\n        return instance;\r\n    }    \r\n}\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">Double Checked Locking Singleton<\/strong><br \/>\nAbove Implementation of Singleton provides thread safety buy has a hit over performance. The performance hit happens when two threads try to get the instance of object in getInstance() method but only one is allowed within Synchronized block while the other needs to wait until the first is done checking irrespective of the instance is already created or not.<\/p>\n<p>In the Below method of Implementing Singleton, we again use Synchronized Block but we do the check for the availability of the object instance even before taking lock.<\/p>\n<p><strong>DCCSingleton.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.singleton;\r\n\r\npublic class DCCSingleton{\r\n\r\n    private static DCCSingletoninstance;\r\n    \r\n    private DCCSingleton(){}\r\n    \r\n   public static DCCSingleton getInstanceUsingDoubleLocking()\r\n   {\r\n    if(instance == null){\r\n        synchronized (DCCSingleton.class) {\r\n            if(instance == null){\r\n                instance = new DCCSingleton();\r\n            }\r\n        }\r\n    }\r\n    return instance;\r\n  }    \r\n}\r\n<\/pre>\n<p>Refer the <a href=\"http:\/\/codethataint.com\/blog\/how-double-checked-locking-works-in-singleton\/\">Link<\/a> for how Double Checked Locking works<\/p>\n<p><strong class=\"ctaHeader3\">ENUM Singleton<\/strong><br \/>\nenum fields are compile time constants, but they are instances of their enum type. And, they&#8217;re constructed when the enum type is referenced for the first time.<br \/>\n<strong>ENUMSingleton.java<\/strong><br \/>\nSimple Singleton using enum for DBConnection<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic enum EnumSingleton\r\n{\r\n    INSTANCE;\r\n\r\n    \/\/ instance vars, constructor\r\n    private final Connection connection;\r\n\r\n    private Singleton()\r\n    {\r\n        \/\/Initialize the connection\r\n        connection = DB.getConnection();\r\n    }\r\n\r\n    public Connection getConnection(){\r\n       return connection;\r\n    }\r\n\r\n    \/\/ Static getter\r\n    public static Singleton getInstance()\r\n    {\r\n        return INSTANCE;\r\n    }\r\n}\r\n<\/pre>\n<p>The way it works we can either use getInstance() method or directly call EnumSingleton.INSTANCE to access connection Object.<\/p>\n<p>The Connection can be created using the Below Code<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n  Connection Conn = Singleton.getInstance().getConnection();\r\n<\/pre>\n<p><strong>Minimal Implementation using ENUM<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic enum MySingleton {\r\n  INSTANCE;   \r\n}\r\n<\/pre>\n<p><strong>In the above code we may get a doubt how the object is created as we have a empty private constructor which is never invoked?.<\/strong><\/p>\n<p>The above code gets converted as one below. Above code has an implicit empty constructor. Lets make it explicit instead,<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic enum MySingleton {\r\n    INSTANCE;\r\n    private MySingleton() {\r\n        System.out.println(&quot;Here&quot;);\r\n    }\r\n}\r\n<\/pre>\n<p>Now when we make a call as below the private constructor is invoked and object gets created<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic static void main(String&#x5B;] args) {\r\n    System.out.println(MySingleton.INSTANCE);\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nHere\r\nINSTANCE\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">Initialization on demand holder idiom<\/strong><br \/>\n<strong>How it works?<\/strong><\/p>\n<ol>\n<li>The Below implementation is a lazy loading and thread safe method of creating Singleton<\/li>\n<li>On calling the getInstance() method the lazySingletonClass would be initialized which in turn makes the INSTANCE to be initialized.<\/li>\n<li>Class initialization is inherently thread-safe and if you can have an object initialized on class initialization the object creation too are thread-safe.<\/li>\n<li>Singleton instance variable will never be created and or initialized until getInstance() is invoked. And again since class initialization is thread-safe the instance variable of IntiailizationOnDemandClassholder will be loaded safely, once and is visible to all threads.<\/li>\n<\/ol>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Singleton {\r\n    private Singleton(){}\r\n\r\n    public static class lazySingletonClass{\r\n      private static final Singleton INSTANCE = new Singleton();\r\n    }\r\n\r\n    public Singleton getInstance(){\r\n        return lazySingletonClass.INSTANCE;\r\n    }\r\n}\r\n<\/pre>\n<table>\n<thead>\n<tr>\n<th><\/th>\n<th>When Object is Created<\/th>\n<th>Thread Safe<\/th>\n<th>Performance<\/th>\n<th>Comments<\/th>\n<\/tr>\n<\/thead>\n<tr>\n<td><strong>Eager Initialization<\/strong><\/td>\n<td>Object Gets Created once the Class is Loaded<\/td>\n<td>Yes<\/td>\n<td>Bad<\/td>\n<td>Object is created everytime when the class is accessed<\/td>\n<\/tr>\n<tr>\n<td><strong>Lazy Initialization<\/strong><\/td>\n<td>Object is Created once required<\/td>\n<td>No<\/td>\n<td><\/td>\n<td>In lazy initialization you give a public API to get the instance. In multi-threaded environment it poses challenges to avoid unnecessary object creation<\/td>\n<\/tr>\n<tr>\n<td><strong>Static Block Initialization<\/strong><\/td>\n<td>Object is Created once Static Block is loaded<\/td>\n<td>Yes<\/td>\n<td>Bad<\/td>\n<td>Not a good idea to load resources from static block as it causes performance hit during app startup<\/td>\n<\/tr>\n<tr>\n<td><strong>Synchronized Method<\/strong><\/td>\n<td>Object is Created once getInstance  is called<\/td>\n<td>Yes<\/td>\n<td>Bad<\/td>\n<td>Thread safety is guaranteed.Slow performance because of whole method  locking is done<\/td>\n<\/tr>\n<tr>\n<td><strong>Synchronized Block<\/strong><\/td>\n<td>Object is Created once getInstance  is called<\/td>\n<td>No<\/td>\n<td><\/td>\n<td>Two singleton instances may be created when context switching happens after checking instance is null<\/td>\n<\/tr>\n<tr>\n<td><strong>Double Checked Locking<\/strong><\/td>\n<td>Object is Created once getInstance  is called<\/td>\n<td>Yes<\/td>\n<td>Good<\/td>\n<td>Instance check is done twice<\/td>\n<\/tr>\n<tr>\n<td><strong>Enum Implementation<\/strong><\/td>\n<td>Object Created using enum is referenced<\/td>\n<td>Yes<\/td>\n<td>Good<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td><strong>Initialization on demand holder idiom<\/strong><\/td>\n<td>Object Created when static class is initiazlied by calling getInstance method<\/td>\n<td>Yes<\/td>\n<td>Good<\/td>\n<td>Class initialization is inherently thread-safe and if you can have an object initialized on class initialization the object creation too are thread-safe<\/td>\n<\/tr>\n<\/table>\n<p><strong class=\"ctaHeader2\">Note<\/strong><br \/>\n<em>Dont be confused between Class Loading and Initialization<\/em>. In the <strong>Initialization on demand holder<\/strong> method of singleton you can easily get confused as the static inner class wont be loaded when the outer class loads.   The implementation relies on the fact that during initialization phase of execution within the Java Virtual Machine (JVM) as specified by the Java Language Specification (JLS) When the class <strong>Singleton <\/strong>is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition <strong>lazySingletonClass<\/strong>within it is not initialized until the JVM determines that <strong>lazySingletonClass<\/strong>must be executed. The static class <strong>lazySingletonClass<\/strong>is only executed when the static method getInstance is invoked on the class<\/p>\n<p> The static class <strong>lazySingletonClass <\/strong>is only executed when the static method getInstance is invoked on the class <strong>Singleton <\/strong>, and the first time this happens the JVM will load and initialize the <strong>lazySingletonClass<\/strong> class. The initialization of the <strong>lazySingletonClass<\/strong>class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something. Since the class initialization phase is guaranteed by the JLS to be sequential, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When Singleton should be used? Singleton should be used incase creation of Object is costly or heavy I.E. DBConnection. It should not be used if the Object is mutable. Eager initialization Lazy initialization Static block initialization Using Synchronized method Using Synchronized block Double Checked Locking Enum Singleton Initialization on demand holder idiom 3 Things are&hellip; <a href=\"https:\/\/codethataint.com\/blog\/different-implementation-of-singleton-pattern\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[227,64],"tags":[],"class_list":["post-2124","post","type-post","status-publish","format-standard","hentry","category-singleton","category-design-patterns"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2124","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=2124"}],"version-history":[{"count":6,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2124\/revisions"}],"predecessor-version":[{"id":5300,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2124\/revisions\/5300"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=2124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=2124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=2124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}