<?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; Rahul Kulshreshtha</title>
	<atom:link href="http://rpktech.com/author/rahul/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>JVM Flags</title>
		<link>http://rpktech.com/2015/02/17/jvm-flags/</link>
		<comments>http://rpktech.com/2015/02/17/jvm-flags/#comments</comments>
		<pubDate>Tue, 17 Feb 2015 14:35:58 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[JVM]]></category>
		<category><![CDATA[java.lang.OutOfMemoryError]]></category>
		<category><![CDATA[JVM Flags]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=79</guid>
		<description><![CDATA[I was writing about &#8220;Unified JVM Logging&#8221; feature which is proposed in Java 9. Then I found it necessary to first share the JVM Flags and what they do. There are thousands of JVM flags out of which we rarely]]></description>
				<content:encoded><![CDATA[<p>I was writing about &#8220;Unified JVM Logging&#8221; feature which is proposed in Java 9. Then I found it necessary to first share the JVM Flags and what they do. There are thousands of JVM flags out of which we rarely use few. Mostly we use them either for GC or Heap Memory tuning or for logging. I read several sites about flags and short-listed few sites to read about them.</p>
<p><strong><span style="text-decoration: underline;">Useful jvm flags</span> : </strong></p>
<p><a href="https://blog.codecentric.de/en/page/3/?s=JVM+flags" target="_blank">https://blog.codecentric.de/en/page/3/?s=JVM+flags</a> (Very good explanation, read all the 8 parts, it&#8217;s interesting)</p>
<p><a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html" target="_blank">http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html</a> (JDK 7)</p>
<p><strong><span style="text-decoration: underline;">List of flags for garbage collection</span> : </strong></p>
<ul>
<li><a href="http://blog.ragozin.info/2013/11/hotspot-jvm-garbage-collection-options.html" target="_blank">http://blog.ragozin.info/2013/11/hotspot-jvm-garbage-collection-options.html</a> (Check the cheat sheet there)</li>
</ul>
<p><strong>Complete list of VM flags :</strong></p>
<ol>
<li><a href="http://jvm-options.tech.xebia.fr/" target="_blank">http://jvm-options.tech.xebia.fr/</a></li>
<li><a href="http://stas-blogspot.blogspot.in/2011/07/most-complete-list-of-xx-options-for.html" target="_blank">http://stas-blogspot.blogspot.in/2011/07/most-complete-list-of-xx-options-for.html</a></li>
</ol>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F17%2Fjvm-flags%2F&amp;linkname=JVM%20Flags" 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%2F17%2Fjvm-flags%2F&amp;linkname=JVM%20Flags" 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%2F17%2Fjvm-flags%2F&amp;linkname=JVM%20Flags" 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%2F17%2Fjvm-flags%2F&amp;title=JVM%20Flags" id="wpa2a_2"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/17/jvm-flags/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JEP 102- Process API Updates</title>
		<link>http://rpktech.com/2015/02/14/jep-102-process-api-updates/</link>
		<comments>http://rpktech.com/2015/02/14/jep-102-process-api-updates/#comments</comments>
		<pubDate>Sat, 14 Feb 2015 07:04:04 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[Java 9 Features]]></category>
		<category><![CDATA[Java 9]]></category>
		<category><![CDATA[JEP 102]]></category>
		<category><![CDATA[Process Api Updates]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=72</guid>
		<description><![CDATA[Process API Updates Java 9 has come with the changes which will let you fetch the pid of a process. Following code shows how to get a pid with Java 9 getPid function internally call getProcessId0 with process&#8217;s handle to]]></description>
				<content:encoded><![CDATA[<p><span style="text-decoration: underline;"><strong>Process API Updates</strong></span></p>
<p>Java 9 has come with the changes which will let you fetch the pid of a process. Following code shows how to get a pid with Java 9</p>
<pre class="brush: java; title: ; notranslate">
ProcessBuilder pb = new ProcessBuilder(&quot;notepad&quot;);
		        Process p = pb.start();

		 System.out.println(&quot;Pid of Process : &quot; + p.getPid());
</pre>
<p>getPid function internally call <strong>getProcessId0</strong> with process&#8217;s handle to retrieve pid. <strong>getProcessId0</strong> is a native method.</p>
<p>Apart from process id, other targeted changes are :</p>
<ul>
<li>Ability to get/set the process name</li>
<li>Ability to enumerate Java virtual machines and processes to get pid, name, state, and perhaps resource usage</li>
<li>Api to do &#8220;End Process Tree&#8221;. <a href="http://rpktech.com/wp-content/uploads/2015/02/EndProcessTree.png"><img class="aligncenter size-full wp-image-73" src="http://rpktech.com/wp-content/uploads/2015/02/EndProcessTree.png" alt="EndProcessTree" width="362" height="285" /></a></li>
</ul>
<p>Thanks Robin for the update, JDK 9 docs are now available here <a href="http://download.java.net/jdk9/docs/api/java/lang/ProcessBuilder.html" rel="nofollow">http://download.java.net/jdk9/docs/api/java/lang/ProcessBuilder.html</a></p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F14%2Fjep-102-process-api-updates%2F&amp;linkname=JEP%20102-%20Process%20API%20Updates" 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%2F14%2Fjep-102-process-api-updates%2F&amp;linkname=JEP%20102-%20Process%20API%20Updates" 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%2F14%2Fjep-102-process-api-updates%2F&amp;linkname=JEP%20102-%20Process%20API%20Updates" 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%2F14%2Fjep-102-process-api-updates%2F&amp;title=JEP%20102-%20Process%20API%20Updates" id="wpa2a_4"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/14/jep-102-process-api-updates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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_6"></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>Java 9 Features</title>
		<link>http://rpktech.com/2015/02/09/java-9-features/</link>
		<comments>http://rpktech.com/2015/02/09/java-9-features/#comments</comments>
		<pubDate>Mon, 09 Feb 2015 06:34:25 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[Java 9 Features]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[Java 9]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=55</guid>
		<description><![CDATA[Java 9 is expected in early 2016. Its always good to know upcoming features in advance so that we will ready to take advantage as soon as they are available. Full list of features targeted in this release can be found]]></description>
				<content:encoded><![CDATA[<p>Java 9 is expected in early 2016. Its always good to know upcoming features in advance so that we will ready to take advantage as soon as they are available. Full list of features targeted in this release can be found <a title="JDK 9 Targeted JEPs" href="http://openjdk.java.net/projects/jdk9/" target="_blank">here</a> (http://openjdk.java.net/projects/jdk9/). Below is a slide show from <a title="Takipi Blog" href="http://blog.takipi.com/java-9-the-ultimate-feature-list/" target="_blank">takipi&#8217;s blog</a> which gives little introduction of upcoming features. I will try to cover them in more detail (examples, usage and explanation) in upcoming blog posts.</p>
<p><iframe style="border: 1px solid #CCC; border-width: 1px; margin-bottom: 5px; max-width: 100%;" src="//www.slideshare.net/slideshow/embed_code/38875307" width="850" height="710" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowfullscreen="allowfullscreen"> </iframe></p>
<div style="margin-bottom: 5px;"></div>
<div style="margin-bottom: 5px;"><strong><a title="Java 9 – The Ultimate Feature List" href="//www.slideshare.net/Takipi/java-9-the-ultimate-feature-list" target="_blank">Java 9 – The Ultimate Feature List</a> </strong> from <strong><a href="//www.slideshare.net/Takipi" target="_blank">Takipi</a></strong></div>
<div style="margin-bottom: 5px;"></div>
<div style="margin-bottom: 5px;"><span style="text-decoration: underline;"><strong>Java 9 Features :</strong></span></div>
<ol>
<li style="margin-bottom: 5px;"><a title="Process API Update" href="http://rpktech.com/2015/02/14/jep-102-process-api-updates/" target="_blank">JEP 102- Process API Updates</a></li>
<li style="margin-bottom: 5px;">JEP 143- Improve Contended Locking</li>
<li style="margin-bottom: 5px;">JEP 158- Unified JVM Logging</li>
<li style="margin-bottom: 5px;">JEP 165- Compiler Control</li>
<li style="margin-bottom: 5px;">JEP 197- Segmented Code Cache</li>
<li style="margin-bottom: 5px;">JEP 199- Smart Java Compilation, Phase Two</li>
<li style="margin-bottom: 5px;">JEP 201- Modular Source Code</li>
<li style="margin-bottom: 5px;">JEP 211- Elide Deprecation Warnings on Import Statements</li>
<li style="margin-bottom: 5px;">JEP 212- Resolve Lint and Doclint Warnings</li>
<li style="margin-bottom: 5px;">JEP 213- Milling Project Coin</li>
<li style="margin-bottom: 5px;">JEP 214- Remove GC Combinations Deprecated in JDK 8</li>
<li style="margin-bottom: 5px;">JEP 216- Process Import Statements Correctly</li>
<li style="margin-bottom: 5px;">JEP 217- Annotations Pipeline 2.0</li>
<li style="margin-bottom: 5px;">JEP 219- Datagram Transport Layer Security (DTLS)</li>
<li>JEP 220- Modular Run-Time Images</li>
<li>JEP 224- HTML5 Javadoc</li>
<li>JEP 228- Add More Diagnostic Commands</li>
<li>JEP 229- Create PKCS12 Keystores by Default</li>
<li>JEP 230- Microbenchmark Suite</li>
<li>JEP 231- Remove Launch-Time JRE Version Selection</li>
<li>JEP 235- Test Class-File Attributes Generated by javac</li>
<li>JEP 236- Parser API for Nashorn</li>
<li>JEP 237- Linux/AArch64 Port</li>
</ol>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F09%2Fjava-9-features%2F&amp;linkname=Java%209%20Features" 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%2F09%2Fjava-9-features%2F&amp;linkname=Java%209%20Features" 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%2F09%2Fjava-9-features%2F&amp;linkname=Java%209%20Features" 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%2F09%2Fjava-9-features%2F&amp;title=Java%209%20Features" id="wpa2a_8"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/09/java-9-features/feed/</wfw:commentRss>
		<slash:comments>0</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_10"></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>
		<item>
		<title>Java Memory Model and Synchronization</title>
		<link>http://rpktech.com/2015/02/03/java-memory-model-and-synchronization/</link>
		<comments>http://rpktech.com/2015/02/03/java-memory-model-and-synchronization/#comments</comments>
		<pubDate>Tue, 03 Feb 2015 14:11:53 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Java Memory Model]]></category>
		<category><![CDATA[memory barrier]]></category>
		<category><![CDATA[synchronized]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=36</guid>
		<description><![CDATA[Java Memory Model The Java memory model specifies how and when different threads can see values written to shared variables by other threads, and how to synchronize access to shared variables when necessary. Java memory model which was revised in Java]]></description>
				<content:encoded><![CDATA[<p><span style="text-decoration: underline;"><strong>Java Memory Model</strong></span></p>
<p>The Java memory model specifies how and when different threads can see values written to shared variables by other threads, and how to synchronize access to shared variables when necessary. Java memory model which was revised in Java 1.5 is still in use in Java 8. Jenkov has explained very well in his <a href="http://tutorials.jenkov.com/java-concurrency/java-memory-model.html" target="_blank">article about JMM</a>. Here is the summary from that article :</p>
<ol>
<li><strong>Primitive</strong> variables inside thread are not shareable, they are kept in thread-stack which is <strong>non-shareable</strong> between threads.</li>
<li><strong>Objects</strong> are created inside heap and heap area is <strong>shareable</strong> between threads.</li>
<li><strong>Object&#8217;s member variabl</strong>e are also stored in heap and hence are <strong>shareable</strong> even though they are primitive. But all the variable declared inside object&#8217;s method are local to that method and they will be store in thread-stack.</li>
<li>Static variables are also stored into heap along with the class definition.</li>
</ol>
<p>Heap is shareable so synchronization is required.  Lets first understand the synchronization and how lock works.</p>
<p><span style="text-decoration: underline;"><strong>Synchronization</strong></span> : In an <a href="http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html" target="_blank">article of &#8220;Brian Goetz&#8221;</a>, synchronization is explained like this</p>
<blockquote><p>Java&#8217;s primary tool for rendering interactions between threads predictably is the <code>synchronized</code> keyword. Many programmers think of <code>synchronized</code> strictly in terms of enforcing a mutual exclusion semaphore (<em>mutex</em>) to prevent execution of critical sections by more than one thread at a time. Unfortunately, that intuition does not fully describe what <code>synchronized</code> means.</p>
<p>The semantics of <code>synchronized</code> do indeed include mutual exclusion of execution based on the status of a semaphore, but they also include rules about the synchronizing thread&#8217;s interaction with main memory. In particular, the acquisition or release of a lock triggers a <strong><em>memory barrier</em></strong> &#8212; a forced synchronization between the thread&#8217;s local memory and main memory. When a thread exits a <code>synchronized</code> block, it performs a write barrier &#8212; it must flush out any variables modified in that block to main memory before releasing the lock. Similarly, when entering a <code>synchronized</code> block, it performs a read barrier &#8212; it is as if the local memory has been invalidated, and it must fetch any variables that will be referenced in the block from main memory.</p>
<p>The proper use of synchronization guarantees that one thread will see the effects of another in a predictable manner.</p></blockquote>
<p>Below examples will show the visibility of variables in Java Memory Model which was explained by Jenkov in his <a href="http://tutorials.jenkov.com/java-concurrency/java-memory-model.html" target="_blank">article</a>.</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F03%2Fjava-memory-model-and-synchronization%2F&amp;linkname=Java%20Memory%20Model%20and%20Synchronization" 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%2F03%2Fjava-memory-model-and-synchronization%2F&amp;linkname=Java%20Memory%20Model%20and%20Synchronization" 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%2F03%2Fjava-memory-model-and-synchronization%2F&amp;linkname=Java%20Memory%20Model%20and%20Synchronization" 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%2F03%2Fjava-memory-model-and-synchronization%2F&amp;title=Java%20Memory%20Model%20and%20Synchronization" id="wpa2a_12"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/03/java-memory-model-and-synchronization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Livelock, Deadlock and Starvation</title>
		<link>http://rpktech.com/2015/02/03/livelock-deadlock-and-starvation/</link>
		<comments>http://rpktech.com/2015/02/03/livelock-deadlock-and-starvation/#comments</comments>
		<pubDate>Tue, 03 Feb 2015 10:08:11 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Deadlock]]></category>
		<category><![CDATA[Livelock]]></category>
		<category><![CDATA[Lock]]></category>
		<category><![CDATA[Starvation]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=31</guid>
		<description><![CDATA[I was looking for a good practical\real example of Livelock and I came across a blog of &#8220;Richard&#8221;. He has shown very good examples of livelock, deadlock and starvation. I was more interested to understand livelock example. Here is the]]></description>
				<content:encoded><![CDATA[<p>I was looking for a good practical\real example of Livelock and I came across a blog of &#8220;Richard&#8221;. He has shown very good examples of livelock, deadlock and starvation. I was more interested to understand livelock example. Here is the link to his blog <a title="Richard Blog" href="https://richardbarabe.wordpress.com/2014/02/21/java-deadlock-livelock-and-lock-starvation-examples/" target="_blank">Richard&#8217;s Blog</a>. Few more examples of livelocks can be found <a title="Livelock examples" href="http://stackoverflow.com/questions/1036364/good-example-of-livelock" target="_blank">here</a></p>
<p>After reading <a title="Richard Blog" href="https://richardbarabe.wordpress.com/2014/02/21/java-deadlock-livelock-and-lock-starvation-examples/" target="_blank">Richard&#8217;s Blog</a>, next question came to my mind, how to prevent the live locks or any other lock and if it happened how application should handle that.</p>
<p>I found this solution given by &#8220;Giuseppe Luciano&#8221; which shows a way to solve live lock when it happens in application. Here is his solution &#8211; <a title="A livelock solution" href="http://www.codeproject.com/Articles/278840/A-livelock-solution" target="_blank">A livelock solution</a>. I believe, &#8220;Prevention is better than cure, so first developer should try how to avoid the deadlock situation while designing the solution. I read multiple blogs and googled also for finding the techniques to prevent deadlock, everyone was pointing to &#8220;order of lock acquisition&#8221; but there were 2 blogs who pointed out few more techniques to prevent deadlock and displayed some more situations where deadlock detection may be missed by the developer. These techniques are :</p>
<ol>
<li>Lock Ordering</li>
<li>Lock Timeout</li>
<li>Deadlock Detection</li>
</ol>
<p>You can read more about these techniques on <a href="http://tutorials.jenkov.com/java-concurrency/deadlock-prevention.html" target="_blank">Jenkov&#8217;s website.</a> Another site explained different scenarios which can cause a deadlock, you can find it on <a href="http://www.javaworld.com/article/2075692/java-concurrency/avoid-synchronization-deadlocks.html" target="_blank">Brian Goetz&#8217;s website.</a> It also shows a solution for live lock problem which was discussed in <a title="Richard Blog" href="https://richardbarabe.wordpress.com/2014/02/21/java-deadlock-livelock-and-lock-starvation-examples/" target="_blank">Richard&#8217;s Blog</a>.</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F03%2Flivelock-deadlock-and-starvation%2F&amp;linkname=Livelock%2C%20Deadlock%20and%20Starvation" 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%2F03%2Flivelock-deadlock-and-starvation%2F&amp;linkname=Livelock%2C%20Deadlock%20and%20Starvation" 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%2F03%2Flivelock-deadlock-and-starvation%2F&amp;linkname=Livelock%2C%20Deadlock%20and%20Starvation" 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%2F03%2Flivelock-deadlock-and-starvation%2F&amp;title=Livelock%2C%20Deadlock%20and%20Starvation" id="wpa2a_14"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/03/livelock-deadlock-and-starvation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JUnit Introduction</title>
		<link>http://rpktech.com/2015/02/02/junit_introduction/</link>
		<comments>http://rpktech.com/2015/02/02/junit_introduction/#comments</comments>
		<pubDate>Mon, 02 Feb 2015 13:09:21 +0000</pubDate>
		<dc:creator><![CDATA[Rahul Kulshreshtha]]></dc:creator>
				<category><![CDATA[JUnit]]></category>

		<guid isPermaLink="false">http://rpktech.com/?p=9</guid>
		<description><![CDATA[JUnit is used for unit testing of Java applications. JUnit and TestNG are two popular unit testing frameworks. In this tutorial I will explore JUnit only. There are two popular version of JUnit &#8211; JUnit 3 and JUnit 4. Below table]]></description>
				<content:encoded><![CDATA[<p>JUnit is used for unit testing of Java applications. JUnit and TestNG are two popular unit testing frameworks. In this tutorial I will explore JUnit only.</p>
<p>There are two popular version of JUnit &#8211; JUnit 3 and JUnit 4. Below table shows few important differences in these versions . Apart from this there is one more important difference that from JUnit 4.7 parallel execution of JUnit test cases is supported.</p>
<p><a href="http://rpktech.com/wp-content/uploads/2015/02/JUnit3-Junit4.png" target="_blank"><img class="aligncenter wp-image-17 size-full" src="http://rpktech.com/wp-content/uploads/2015/02/JUnit3-Junit4.png" alt="JUnit3-Junit4" width="762" height="374" /></a></p>
<p>&nbsp;</p>
<p><strong>JUnit 3.x Sample</strong></p>
<pre class="brush: java; title: ; notranslate">import junit.framework.*;
public class MoneyTest extends TestCase {
	private Money f12CHF;			// fixtures
	private Money f14CHF;

	protected void setUp() {		// create the test data
		f12CHF = new Money(12, &quot;CHF&quot;);
		f14CHF = new Money(14, &quot;CHF&quot;);
	}
   void testAdd() {				// create the test data
		Money expected = new Money(26, “CHF”);
		assertEquals(“amount not equal”,
                     expected,f12CHF.add(f14CHF);
	}
	...
}
</pre>
<p><strong>JUnit 4.x Sample</strong></p>
<pre class="brush: java; title: ; notranslate">
import junit.framework.*;
import org.junit.*;
import static org.junit.Assert.*;
public class MoneyTest &lt;del&gt;extends TestCase&lt;/del&gt; {
	private Money f12CHF;
	private Money f14CHF;

	@Before
        public void setUp() // setup, teardown function names are not mandatory now as we have annotations now
        {
		f12CHF = new Money(12, &quot;CHF&quot;);    // - the fixture
		f14CHF = new Money(14, &quot;CHF&quot;);
	}
	@Test
        public void testAdd() // create the test data
        {
		Money expected = new Money(26, “CHF”);
		assertEquals(“amount not equal”,
                     expected,f12CHF.add(f14CHF));
	}
	...
}

</pre>
<p><strong>Following changes were happened in JUnit 4.x</strong></p>
<ol>
<li>No need to start test method name with prefix &#8220;test&#8221;.</li>
<li>@BeforeClass and @AfterClass were introduced
<ol>
<li>@BeforeClass method &#8211; executes <strong>only once</strong>; before the first test method</li>
<li>@AfterClass method &#8211; executes <strong>only once</strong>; after the last test method</li>
</ol>
</li>
<li>Instead of setup and tearDown now JUnit 4 has @Before and @After annotations.
<ol>
<li>@Before method &#8211; executes <strong>every time; </strong>before the test method.</li>
<li>@After method &#8211; executes <strong>every time; </strong>after the test method.</li>
</ol>
</li>
<li>@Ignore was introduced to skip a test case while running.</li>
<li>&#8220;expected&#8221; was introduced to tell JUnitRunner that what exception we are expecting. Example : @Test(expected=ArithmeticException.class)</li>
<li>&#8220;timeout&#8221; was introduced to put a time limit on a testcase. If test does not complete in that time limit, an exception will raise with message &#8220;test timed out after xxx milliseconds&#8221;</li>
</ol>
<p>Next posts will show the working examples with these annotations.</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Frpktech.com%2F2015%2F02%2F02%2Fjunit_introduction%2F&amp;linkname=JUnit%20Introduction" 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%2F02%2Fjunit_introduction%2F&amp;linkname=JUnit%20Introduction" 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%2F02%2Fjunit_introduction%2F&amp;linkname=JUnit%20Introduction" 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%2F02%2Fjunit_introduction%2F&amp;title=JUnit%20Introduction" id="wpa2a_16"></a></p>]]></content:encoded>
			<wfw:commentRss>http://rpktech.com/2015/02/02/junit_introduction/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
