<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java and Me &#187; Singleton</title>
	<atom:link href="http://rpktech.com/tag/singleton/feed/" rel="self" type="application/rss+xml" />
	<link>http://rpktech.com</link>
	<description>An Interesting Journey</description>
	<lastBuildDate>Sun, 22 Nov 2015 11:01:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.41</generator>
	<item>
		<title>Safe Singleton</title>
		<link>http://rpktech.com/2015/02/12/safe-singleton/</link>
		<comments>http://rpktech.com/2015/02/12/safe-singleton/#comments</comments>
		<pubDate>Thu, 12 Feb 2015 15:13:52 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Deserialization]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[Safe]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=65</guid>
		<description><![CDATA[In my previous article, we saw how singleton can be created. But there can be some scenarios where serialization and de-serialization of singleton object is required and that can create multiple objects of a singleton class. This can be prevented if]]></description>
				<content:encoded><![CDATA[<p>In my <a title="Lazy Initialization and Singleton" href="http://rpktech.com/2015/02/04/lazy-initialization-in-multi-threaded-environment/" target="_blank">previous article</a>, we saw how singleton can be created. But there can be some scenarios where serialization and de-serialization of singleton object is required and that can create multiple objects of a singleton class. This can be prevented if we will use enum instead of class for singleton. <strong>Note that enum methods are not thread-safe so I used synchronized there. </strong>Below is an example, how we can use enum for creating a safe singleton. <code>Date</code> is <strong>not</strong> thread safe, so I highly recommend returning a copy and replacing the instance with a copy when changes are made.</p>
<pre class="brush: java; title: ; notranslate">
package com.rpktech.poc;
import java.util.Date;

public enum SingletonWithEnum {
	INSTANCE;	

	private volatile int count;
	private volatile Date date;		

        public int getCount() {	return count;}

	public void setCount(int countParam) { synchronized(this){ count = countParam; }}

	public Date getDate() {  return new Date(date.getTime());}

	public void setDate(Date dateParam) { synchronized(this){ date = (Date) dateParam.clone();}}

	public String printObject() {
		return &quot;Singleton [count=&quot; + getCount() + &quot;, date=&quot; + getDate() + &quot;]&quot;;
	}

}
</pre>
<p>To test it with serialization and de-serialization I have used google&#8217;s GSON library.</p>
<pre class="brush: java; title: ; notranslate">

package com.rpktech.poc;

import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class TestSingletonWithEnum{
	public static void main(String[] s)
	{
		SingletonWithEnum object1 = SingletonWithEnum.INSTANCE;

		object1.setCount(5);
		object1.setDate(new Date());		

		Gson gson = new GsonBuilder().create();

		SingletonWithEnum object2 = gson.fromJson(gson.toJson(object1), SingletonWithEnum.class);

		object2.setCount(3);

		if(object1 == object2)
			System.out.println(&quot;Same&quot;);
		else
			System.out.println(&quot;Differnent&quot;);

		System.out.println(object1.printObject());
		System.out.println(object2.printObject());

	}
}
</pre>
<p><span style="text-decoration: underline;"><strong>Output</strong></span></p>
<pre class="brush: plain; title: ; notranslate">
Same
Singleton [count=3, date=Thu Feb 12 20:39:47 IST 2015]
Singleton [count=3, date=Thu Feb 12 20:39:47 IST 2015]
</pre>
<p>Enum is good choice for singleton because :</p>
<ol>
<li>Enum fields will be initialized when INSTANCE is first accessed or when enum is first accessed. So we can achieve lazy initialization functionality by not using INSTANCE until it (singleton object) is required.</li>
<li>You can not extend a proper Singleton since it&#8217;s supposed to have a private constructor, so using an enum is fine in place of class (<em>Effective Java Item 2: Enforce the singleton property with a private constructor)</em></li>
</ol>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F12%2Fsafe-singleton%2F&amp;linkname=Safe%20Singleton" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F12%2Fsafe-singleton%2F&amp;linkname=Safe%20Singleton" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F12%2Fsafe-singleton%2F&amp;linkname=Safe%20Singleton" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share#url=http%3A%2F%2Frpktech.com%2F2015%2F02%2F12%2Fsafe-singleton%2F&amp;title=Safe%20Singleton" id="wpa2a_2"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/12/safe-singleton/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lazy Initialization in Multi-threaded Environment</title>
		<link>http://rpktech.com/2015/02/04/lazy-initialization-in-multi-threaded-environment/</link>
		<comments>http://rpktech.com/2015/02/04/lazy-initialization-in-multi-threaded-environment/#comments</comments>
		<pubDate>Wed, 04 Feb 2015 15:44:21 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[dcl]]></category>
		<category><![CDATA[Demand Holder Idiom]]></category>
		<category><![CDATA[Double checked locking]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=41</guid>
		<description><![CDATA[Lazy Initialization is a way of improving performance of application. In lazy initialization objects are not initialized until they are needed. This saves the cost of creating objects and wasting memory until they are actually needed. Proxy Objects in Hibernate]]></description>
				<content:encoded><![CDATA[<p>Lazy Initialization is a way of improving performance of application. <strong>In lazy initialization objects are not initialized until they are needed</strong>. This saves the cost of creating objects and wasting memory until they are actually needed. Proxy Objects in Hibernate are good example of lazy initialization. Let&#8217;s see lazy initialization when there is no multi-threading.</p>
<pre class="brush: java; title: ; notranslate">
class SomeClass {
  private Resource resource = null;
  public Resource getResource() {
    if (resource == null)
      resource = new Resource();
    return resource;
  }
}
</pre>
<p>As you can see above &#8220;resource&#8221; will be initialized only when it will be needed. But this will not work in multi-threaded environment. Because multiple threads can be at line 5 at the same time and it will create multiple objects. To prevent this we can use synchronized keyword at the method level but creating &#8220;synchronized methods&#8221; are bad for performance, it cost more. So next thought comes to put synchronized block inside the function. Now code look like below</p>
<pre class="brush: java; title: ; notranslate">
class SomeClass {
  private Resource resource = null;
  public Resource getResource() {
    if (resource == null) {
      synchronized(SomeClass.class){
        if (resource == null)
          resource = new Resource();
      }
    }
    return resource;
  }
}
</pre>
<p>Above code seems certainly better. It synchronizes &#8220;resource&#8221; so at a time only one thread can enter and initialize the resource. This implementation is called &#8220;Double checking lock&#8221; or DCL. But this is also having one issue with Java Memory Model. That is <strong>partially initialized objects can be returned</strong>. DCL has been explained very well in <a href="http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html" target="_blank">Brain Goetz article here</a>. I will summarize it in the following statement.</p>
<blockquote><p>When JVM executes multiple instructions, it can rearrange instructions such that actual result will not change but performance will increase. So when doing <strong>new Resource()</strong>, it can first allocate memory for object, return the reference to that memory location into &#8220;resource&#8221; variable and then it will start initialization of inner fields by calling constructor of &#8220;Resource object&#8221;. As the reference is returned before the constructor is called, it will result into partially created object which is undesirable because its a multi-threading environment and other threads can start using that reference when they found it <strong>&#8220;not null&#8221;.</strong></p></blockquote>
<p>This problem is very rare and it does not come on all the platforms because few JVMs actually implement the JMM properly. But we can overcome this issue by scarifying performance optimization which was happening by reordering of instructions. If we declare our lazy initialized objects to be <strong>volatile</strong> then JVM will not rearrange the order of instructions. <strong>Note that all the fields inside resource should also be volatile. </strong>If your resource class is some third party class and internal fields are not volatile then there are still chances of partially constructed objects. So this way we can improve more but it is still not fixed fully. After implementing volatile; now code will look like this</p>
<pre class="brush: java; title: ; notranslate">
class SomeClass {
  private volatile Resource resource = null;
  public Resource getResource() {
    if (resource == null) {
      synchronized(SomeClass.class){
        if (resource == null)
          resource = new Resource();
      }
    }
    return resource;
  }
}
</pre>
<p>The above solution(partially fixed) works from Java 1.5 or later. Brain Goetz had written another article in which he showed a fully working solution for lazy initialization. But it works only for static fields where there should be only one instance of the field shared across all the objects like &#8220;db connection instance&#8221;. Here is the <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl" target="_blank">JSR-133</a> which covers DCL issue and introduced <strong>&#8220;Demand Holder idiom&#8221;</strong>. I will summaries it here.</p>
<blockquote><p>Class initialization is inherently thread-safe and if you can have an object initialized on class initialization the object creation too are thread-safe.</p></blockquote>
<p>So here is the less complicated solution of <strong>Lazy Initialization In Multi-threaded environment for static fields.</strong></p>
<pre class="brush: java; title: ; notranslate">
class SomeClass {

	  public Resource getResource() {
	    return ResourceHolder.instance;
	  }

	  // Resource Holder
	  private static class ResourceHolder{
	         private static final Resource instance = new Resource();
	  }
}
</pre>
<p>In above example resource will be only be created when getResource is called first time. As the class initialization is thread-safe so resource creation will automatically be thread-safe. But notice that inner class is static so this instance will be static. Static is must here, we can not remove it to support lazy initialization of non-static fields because if we remove &#8220;static&#8221; from inner class then we can not write &#8220;ResourceHolder.instance&#8221;. We have to create an object of that and <strong>object creation is not thread-safe only class loading is thread safe</strong>. This will also work for <b>lazy initialization of singleton class because internally they have static field.</b></p>
<p><strong>Note that if you have multiple static fields for lazy initialization then you have to create multiple static inner classes.</strong></p>
<p>Here is the lazily initialized thread-safe singleton class</p>
<pre class="brush: java; title: ; notranslate">
public class MySingletonClass{

   private MySingletonClass(){

   }
   public static MySingletonClass getInstance(){
         return IntiailizationOnDemandClassHolder.instance;
   }

   private static class IntiailizationOnDemandClassHolder{
         private static final MySingletonClass instance = new MySingletonClass();

   }

}
</pre>
<p>Tom has compared performance of all the approched in his <a href="http://literatejava.com/jvm/fastest-threadsafe-singleton-jvm/" target="_blank">blog</a>.</p>
<table>
<tbody>
<tr>
<th>TECHNICAL APPROACH</th>
<th>TOTAL TIME</th>
<th>MINUS OVERHEAD</th>
<th>PER OPERATION</th>
</tr>
<tr>
<td>‘synchronized’ method</td>
<td>858 ms</td>
<td>834 ms</td>
<td>83.4 ns</td>
</tr>
<tr>
<td>double-checked locking, ‘volatile’ field</td>
<td>39.27 ms</td>
<td>15.79 ms</td>
<td>1.58 ns</td>
</tr>
<tr>
<td><b>inner-class static init</b></td>
<td><b>33.4 ms</b></td>
<td><b>9.92 ms</b></td>
<td><b>0.99 ns</b></td>
</tr>
<tr>
<td><i>loop &amp; hashcode overhead</i></td>
<td></td>
<td><i>23.48 ms</i></td>
<td><i>2.35 ns</i></td>
</tr>
</tbody>
</table>
<p>This is over 25 times faster on our benchmark!</p>
<p>Above singleton will work fine but still sometimes people want to protect singleton from cloning, reflection and de-serialization &amp; serialization so there will not be more than one objects of a singleton class. <a title="Safe Singleton" href="http://rpktech.com/2015/02/12/safe-singleton/" target="_blank">My next article</a> will explain that more in detail.</p>
<p><a title="Safe Singleton" href="http://rpktech.com/2015/02/12/safe-singleton/" target="_blank"><span style="text-decoration: underline;"><strong>Continue to Safe Singleton</strong></span></a></p>
<p><span style="text-decoration: underline;"><strong>References</strong></span></p>
<ul>
<li><a href="http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html" target="_blank">http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking&#8211;clever&#8211;but-broken.html</a></li>
<li><a href="http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl" target="_blank">http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl</a></li>
<li><a href="http://stackoverflow.com/questions/5958767/is-double-checked-locking-is-broken-a-java-only-thing?rq=1" target="_blank">http://stackoverflow.com/questions/5958767/is-double-checked-locking-is-broken-a-java-only-thing?rq=1</a></li>
<li><a href="http://stackoverflow.com/questions/4926681/why-is-double-checked-locking-broken-in-java?rq=1" target="_blank">http://stackoverflow.com/questions/4926681/why-is-double-checked-locking-broken-in-java?rq=1</a></li>
<li><a href="http://stackoverflow.com/questions/3578604/how-to-solve-the-double-checked-locking-is-broken-declaration-in-java" target="_blank">http://stackoverflow.com/questions/3578604/how-to-solve-the-double-checked-locking-is-broken-declaration-in-java</a></li>
<li><a href="http://www.javamex.com/tutorials/double_checked_locking_fixing.shtml" target="_blank">http://www.javamex.com/tutorials/double_checked_locking_fixing.shtml</a></li>
<li><a href="http://literatejava.com/jvm/fastest-threadsafe-singleton-jvm/" target="_blank">http://literatejava.com/jvm/fastest-threadsafe-singleton-jvm/</a></li>
</ul>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F04%2Flazy-initialization-in-multi-threaded-environment%2F&amp;linkname=Lazy%20Initialization%20in%20Multi-threaded%20Environment" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F04%2Flazy-initialization-in-multi-threaded-environment%2F&amp;linkname=Lazy%20Initialization%20in%20Multi-threaded%20Environment" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F04%2Flazy-initialization-in-multi-threaded-environment%2F&amp;linkname=Lazy%20Initialization%20in%20Multi-threaded%20Environment" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share#url=http%3A%2F%2Frpktech.com%2F2015%2F02%2F04%2Flazy-initialization-in-multi-threaded-environment%2F&amp;title=Lazy%20Initialization%20in%20Multi-threaded%20Environment" id="wpa2a_4"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/04/lazy-initialization-in-multi-threaded-environment/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
