<?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>Thread.currentThread().join() &#187; Java</title>
	<atom:link href="http://www.ashishpaliwal.com/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ashishpaliwal.com/blog</link>
	<description>From Programmer, For Programmers</description>
	<lastBuildDate>Tue, 23 Aug 2011 03:53:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Updating Google Calendar with MS Project Tasks &#8211; 2 &#8211; Revisited</title>
		<link>http://www.ashishpaliwal.com/blog/2011/08/updating-google-calendar-with-ms-project-tasks-2-revisited/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/08/updating-google-calendar-with-ms-project-tasks-2-revisited/#comments</comments>
		<pubDate>Tue, 23 Aug 2011 03:53:36 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Application Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Google Calendar]]></category>
		<category><![CDATA[MS Project]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=648</guid>
		<description><![CDATA[This is the 2nd part in the series. Please refer to Updating Google Calendar with MS Project Tasks - Revisited for Part 1, including how to build the code. In the previous post we saw, how to list all the Calendar's. In this post we shall build upon the code to list all the calendar's [...]]]></description>
			<content:encoded><![CDATA[<p>This is the 2nd part in the series. Please refer to <a href="http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/">Updating Google Calendar with MS Project Tasks - Revisited</a> for Part 1, including how to build the code.</p>
<p>In the previous post we saw, how to list all the Calendar's. In this post we shall build upon the code to list all the calendar's for a given user account, and update the MS Project tasks to the selected calendar.</p>
<p>We shall need to following three steps:</p>
<ul>
<li>List Calendars and select one</li>
<li>Parse MS Project tasks and convert them to Calendar events</li>
<li>Update Google Calendar with Events</li>
</ul>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h3>Step 1: List All calendar's</h3>
<p>We have already seen the code for this in previous <a href="http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited">post</a></p>
<h3> Step 2: Parse MS Project task and convert to Calendar Event</h3>
<p>Lets look at the code for the conversion</p>
<pre class="brush: java">
protected CalendarEventEntry convertTaskToCalenderEntry(Task task) {
    System.out.println(&quot;Task &quot;+task);
    CalendarEventEntry eventEntry = new CalendarEventEntry();
    eventEntry.setTitle(new PlainTextConstruct(task.getName()));

    When date = new When();
    date.setStartTime(new DateTime(task.getStart()));
    eventEntry.addTime(date);
    return eventEntry;
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
The code takes Start and End date of task, as well as title, and creates an CalendarEventEntry for the same. There can be additional logic built into this, like filtering events based on some rules etc.</p>
<h3> Step 3: Updating entries into Google Calendar </h3>
<pre class="brush: java">
public void updateCalenderWithEntry(List&lt;Task&gt; tasks, CalendarService calendarService, URL url) {
    for (Task task : tasks) {
        CalendarEventEntry entry = convertTaskToCalenderEntry(task);
        try {
            calendarService.insert(url, entry);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
Here we just iterate through the tasks and update the events using CalendarService. The Calendar URL can be retrieved from the CalendarEntry class.</p>
<p>A complete working example is part of com.ashishpaliwal.mpputils.examples.MppToGoogleCalendar</p>
<h4>Using the sample program</h4>
<p>>com.ashishpaliwal.mpputils.examples.MppToGoogleCalendar [MPP File] [Google User Name] [password]</p>
<h3>What's Next?</h3>
<p>Eager to hear from user, what they would like to see. Adding a UI and out-of-box working package is something that would be good. However, please do try using this and I shall try my best to improve this.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/08/updating-google-calendar-with-ms-project-tasks-2-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hunting down CPU hogging Java Thread</title>
		<link>http://www.ashishpaliwal.com/blog/2011/08/finding-java-thread-consuming-high-cpu/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/08/finding-java-thread-consuming-high-cpu/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 21:48:21 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[CPU]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=632</guid>
		<description><![CDATA[Most of us have encountered a situation to find cause of high CPU usage in Java application. Profiling is the best way, but at times running Profiler in production is not an option. Fortunately, there is a simple way, if you are running your app on *nix. Lets explore how to find this. Find the [...]]]></description>
			<content:encoded><![CDATA[<p>Most of us have encountered a situation to find cause of high CPU usage in Java application. Profiling is the best way, but at times running Profiler in production is not an option. Fortunately, there is a simple way, if you are running your app on *nix.</p>
<p>Lets explore how to find this.</p>
<ul>
<li>Find the pid of the application, using <em>top</em> or <em>jps</em> command</li>
<li>Once you get the pid, run following command<br />
   <strong><strong>$ ps -L pid</strong></strong>
</li>
<p>We get an output as shown in the figure<br />
<div id="attachment_635" class="wp-caption aligncenter" style="width: 410px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/08/Screen-shot-2011-08-10-at-2.39.54-AM1.png"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/08/Screen-shot-2011-08-10-at-2.39.54-AM1.png" alt="" title="ps output" width="400" height="216" class="size-full wp-image-635" /></a><p class="wp-caption-text">ps output</p></div></p>
<p>The output displays all the Threads in the application along with the time spent. Find the Thread that has spent highest time in execution (Entry circled on right). Once we identify this, get the LWP ID of the Thread (Entry circled on left).</p>
<li>Using <em>jstack</em> or <em>visualvm</em>, take a Thread dump.</li>
<li>Convert LWP ID to Hex and search for the ID in Thread dump. </li>
</ul>
<p>Then you can narrow down the thread which is consuming max CPU and investigate further.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/08/finding-java-thread-consuming-high-cpu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Updating Google Calendar with MS Project Tasks &#8211; Revisited</title>
		<link>http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 11:04:51 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Google Calendar]]></category>
		<category><![CDATA[MS Project]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=619</guid>
		<description><![CDATA[Back in 2008, wrote the post on Updating Google Calendar with MS Project. Since then, lot many people had asked for the code, and myself felt that getting the code on github would be great. I shall keep complete the post in 2 parts, starting with setup, listing the calendars and then winding up with [...]]]></description>
			<content:encoded><![CDATA[<p>Back in 2008, wrote the post on <a href="http://www.ashishpaliwal.com/blog/2008/10/updating-google-calendar-with-ms-project-tasks/">Updating Google Calendar with MS Project</a>. Since then, lot many people had asked for the code, and myself felt that getting the code on github would be great. I shall keep complete the post in 2 parts, starting with setup, listing the calendars and then winding up with updating Google Calendar with MS Project entries.</p>
<p>To begin, you can get the code form github at following location</p>
<p><a href="https://github.com/paliwalashish/mpputils">https://github.com/paliwalashish/mpputils</a></p>
<h2>Building the code</h2>
<p>To build the code and download the dependencies, please refer to the wiki page <a href="https://github.com/paliwalashish/mpputils/wiki/Build">https://github.com/paliwalashish/mpputils/wiki/Build</a></p>
<h2> Retrieving Calendar's</h2>
<p>Now lets move to retrieving the list of all the Calendar's for a user<br />
The code is simple enough, here is the function which does the</p>
<pre class="brush: java">
public static List&lt;CalendarEntry&gt; getAllCalendars(String userName, String password) throws Exception {
        CalendarService myService = new CalendarService(&quot;CalendarService-&quot;+userName);
        myService.setUserCredentials(userName, password);

        // Send the request and print the response
        URL feedUrl = new URL(&quot;https://www.google.com/calendar/feeds/default/allcalendars/full&quot;);
        CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);

        return resultFeed.getEntries();
    }
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>This snippet shall return all the Calendar's for the specified user account.</p>
<p>The code has an example of using the same. Please refer to <em><strong>com.ashishpaliwal.mpputils.examples.ListAllCalendars</strong></em> class on the usage.</p>
<p>In the next part we shall see the code for updating of Google Calendar with MS Project task.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60TextOnly */
google_ad_slot = "8279148993";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Simple LRU Cache</title>
		<link>http://www.ashishpaliwal.com/blog/2011/05/a-simple-lru-cache/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/05/a-simple-lru-cache/#comments</comments>
		<pubDate>Fri, 13 May 2011 16:19:37 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=612</guid>
		<description><![CDATA[Recently, while working on a module has a need of very light weight fixed size LRU cache. There are definitely lot of caching solutions around, but decided to try a simple Map based solution. Surprisingly, the solution using LinkedHashMap turned out to be simplest. Here is the snippet. Removed all additional validation and other stuff [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, while working on a module has a need of very light weight fixed size LRU cache. There are definitely lot of caching solutions around, but decided to try a simple Map based solution. Surprisingly, the solution using LinkedHashMap turned out to be simplest.</p>
<p>Here is the snippet. Removed all additional validation and other stuff for simplicity.</p>
<pre class="brush: java">
public class LruCache {
    // cache data holder
    Map&lt;Object, Object&gt; cache;

    // Max size
    private int maxCacheSize;

    public LruCache(int maxSize) {
        this.maxCacheSize = maxSize;
        cache = new LinkedHashMap(maxSize, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() &gt; maxCacheSize;
            }
        };
    }

    public void put(Object key, Object value) {
        cache.put(key, value);
    }

    public Object get(Object key) {
        return cache.get(key);
    }
}
</pre>
<p>The implementation is fairly simple. The third parameter while initialization of LinkedHashMap is the key. a value of "true" means the implementation should use access-order while evicting the entry.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/05/a-simple-lru-cache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta</title>
		<link>http://www.ashishpaliwal.com/blog/2009/11/getting-started-with-terracotta/</link>
		<comments>http://www.ashishpaliwal.com/blog/2009/11/getting-started-with-terracotta/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 10:51:40 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Application Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[Terracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=340</guid>
		<description><![CDATA[Abstract In this small post we shall explore Terracotta, a leading pure Java Scalability platform. The discussion is based on the AtomicInteger example from Terracotta site, which shows how to implement a Cluster wide id generator (Actually it’s the Sequencer example, but to keep my steps simple had used AtomicInteger). The reason why I choose [...]]]></description>
			<content:encoded><![CDATA[<h2><strong>Abstract</strong></h2>
<p>In this small post we shall explore Terracotta, a leading pure Java Scalability platform. The discussion is based on the AtomicInteger example from Terracotta site, which shows how to implement a Cluster wide id generator (Actually it’s the Sequencer example, but to keep my steps simple had used AtomicInteger). The reason why I choose this example was coz of a very similar requirement that I had to implement in Clustered J2EE application.<br />
Terracotta is well known and needs no introduction <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2><strong>About problem Statement</strong></h2>
<p>Well, I needed a simple solution to have<br />
•	Cluster wide unique id’s<br />
•	Less frequent access to these id’s<br />
•	Optional Persistence</p>
<p><strong>NOTE:</strong> Please note that the current example is slightly modified version of example from terracotta.org.</p>
<h2>Pre-requisite</h2>
<p>To run this example, you need to have following installed<br />
•	Terracotta<br />
•	And JDK offcourse <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
Let’s take a look at the sample code first</p>
<pre class="brush: java">
import java.util.concurrent.atomic.*;

public class IdGenerator
{

private AtomicInteger masterCounter = new AtomicInteger(0);

private AtomicInteger slaveCounter = new AtomicInteger(1024);

public int getNewMasterId()
{
int newId = masterCounter.getAndIncrement();
System.out.println(&quot;Master Id is: &quot; + newId);
return newId;
}

public int getNewSlaveId()
{
int slaveId = slaveCounter.getAndIncrement();
System.out.println(&quot;Slave Id is: &quot; + slaveId);
return slaveId;
}

public static void main(String[] args)
{
new IdGenerator().getNewMasterId();
}
}
</pre>
<p>The code has two fields ids master and slave, of which master id need to be unique cluster wide. The code is pretty straight forward, and there is nothing to explain. The id’s are generated by simple getAndIncrement() API.</p>
<p>Lets see the tc-config.xml</p>
<pre class="brush: xml">

&lt;tc:tc-config xmlns:tc=&quot;http://www.terracotta.org/config&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://www.terracotta.org/schema/terracotta-4.xsd&quot;&gt;

&lt;application&gt;
&lt;dso&gt;
&lt;roots&gt;
&lt;root&gt;
&lt;field-name&gt;IdGenerator.masterCounter&lt;/field-name&gt;
&lt;/root&gt;
&lt;/roots&gt;
&lt;/dso&gt;
&lt;/application&gt;
&lt;/tc:tc-config&gt;
</pre>
<p>Since only master Id needed to be unique in this case, hence the configuration</p>
<p>Let’s look at the deployment architecture</p>
<div id="attachment_343" class="wp-caption aligncenter" style="width: 310px"><img class="size-medium wp-image-343" title="nodes" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2009/11/nodees-300x134.png" alt="Deployment Architecture" width="300" height="134" /><p class="wp-caption-text">Deployment Architecture</p></div>
<p>The application was to run on 3 nodes (3 JVM’s on same machine) and one Terracotta server running.<br />
Before we get into running this application, lets take a look at some useful scripts provided by Terracotta<br />
•	<strong>dso-java (bat|sh)</strong> – startup script that bootstraps Terracotta libraries to your application<br />
•	<strong>start-tc-server (bat|sh)</strong> – Script to start Terracotta Server. It is mandatory to start Terracotta Server before running Clients</p>
<p>Let’s run the application<br />
1.	Compile the application. There is no dependency on TC libraries.<br />
2.	First Start the terracotta Server using script start-tc-server<br />
3.	Run 3 separate JVM with command “dso-java IdGenerator”<br />
That’s it. Our first application is running. If we observe the console output, you can see that we have unique id’s for each invocation.</p>
<h2>References:</h2>
<p>Source code for Terracotta examples - http://svn.terracotta.org/svn/forge/cookbook</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2009/11/getting-started-with-terracotta/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Executors in Action &#8211; Part 1 &#8211; The Life cycle</title>
		<link>http://www.ashishpaliwal.com/blog/2009/09/executors-in-action-part-1-the-life-cycle/</link>
		<comments>http://www.ashishpaliwal.com/blog/2009/09/executors-in-action-part-1-the-life-cycle/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 10:59:36 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=322</guid>
		<description><![CDATA[From the Javadoc … interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. Indeed, Executors provide a more robust and easy mechanism for decoupling of submitting a task, from [...]]]></description>
			<content:encoded><![CDATA[<p>From the Javadoc</p>
<p>… interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads.</p>
<p>Indeed, Executors provide a more robust and easy mechanism for decoupling of submitting a task, from its execution.</p>
<p>In this series, we shall explore this concurrency construct in detail.</p>
<p>NOTE: Have tried to avoid explaining what is already available in javadoc.</p>
<p>Let’s first see the lifecycle of an Executor</p>
<p>ExecutorService extends the Executor interface, adding a bunch of life cycle methods.</p>
<p><div id="attachment_328" class="wp-caption alignnone" style="width: 475px"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2009/09/executorstatemachine1.png" alt="Executor Life Cycle" title="executorstatemachine1" width="465" height="220" class="size-full wp-image-328" /><p class="wp-caption-text">Executor Life Cycle</p></div><br />
Let’s create a simple program to demonstrate the same</p>
<pre class="brush: java">
public static void main(String[] args) {
// Executor doesn&#039;t exist before this step
// Executor created and moved to running state
ExecutorService executor = Executors.newSingleThreadExecutor();

// Executor into running state
executor.execute(new Runnable() {
public void run() {
System.out.println(&quot;Running...&quot;);
}
});

// Lets shutdown
executor.shutdown();

System.out.println(&quot; isShutdown = &quot;+executor.isShutdown());
System.out.println(&quot; isTermianted = &quot;+executor.isTerminated());
}
</pre>
<p>The program depicts the complete lifecycle. Please see the comments inline in the code</p>
<p>Initially the Executor doesn’t exist. When we create an Executor, using Executor’s we have it in Ready state (ready to accept tasks for execution).<br />
Once we submit a task for execution, the Executor moves to running state. Once it completes the task, it moves back to ready state.</p>
<p>Once we call <strong>shutdown()</strong> on Executor, it begins its shutdown cycle. Once it is completed it moves to Terminated state.</p>
<p>There are couple of things that need to be noted after shutdown is initiated. An Executor can be executing or may have couple of tasks pending to be executed.</p>
<p>Calling <strong>shutdown()</strong> initiates an orderly shutdown, means all the pending tasks shall be completed, but new tasks won’t be accepted</p>
<p>Calling <strong>shutdownNow()</strong> initiates a shutdown, by trying to halt the processing the tasks by interrupting the threads. The method returns a list of Runnable’s which were not executed. Programs can use them to reschedule them later or discard them.</p>
<p>What will happen, if we submit a task once shutdown has been initiated?<br />
This situation can be handled by using RejectExecutionHandler. The default implementation simply discards the tasks. We can have the custom logic to handle the tasks that couldn’t be executed.</p>
<p>Upcoming topic – Exploring a little on ScheduledExecutorService</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2009/09/executors-in-action-part-1-the-life-cycle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>If-else vs switch – Which is better?</title>
		<link>http://www.ashishpaliwal.com/blog/2009/08/if-else-vs-switch-%e2%80%93-which-is-better/</link>
		<comments>http://www.ashishpaliwal.com/blog/2009/08/if-else-vs-switch-%e2%80%93-which-is-better/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 02:16:35 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=303</guid>
		<description><![CDATA["Use switch instead of if-else, its more readable and has better performance." I have to admit that this was one of my favorite code review comment. Until one fine day, while hacking Apache Sanselan's image format decoding function, I tried optimizing the code based on the same comments and while benchmark there was hardly any [...]]]></description>
			<content:encoded><![CDATA[<p>"Use switch instead of if-else, its more readable and has better performance." I have to admit that this was one of my favorite code review comment. Until one fine day, while hacking Apache Sanselan's image format decoding function, I tried optimizing the code based on the same comments and while benchmark there was hardly any difference. I thought about investigating it further. Though found some interesting mail chains, though about posting my finding.</p>
<p>To begin with decided to run some samples on switch and if-else constructs and analyze further.</p>
<p>Wrote three function<br />
1. For if-else - a if-else ladder based on int comparisons<br />
2. For Switch - switch with 21 cases, from 1 to 20<br />
3. For Switch - switch with sparse random values</p>
<p>The reason for choosing two functions for switch was this statement from <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14942">VM spec</a> <em>"Compilation of switch statements uses the tableswitch and lookupswitch instructions"</em></p>
<p>Lets see the function codes</p>
<h3>if-else</h3>
<pre class="brush: java">
public static void testIfElse(int jumpLabel) {
if(1 == jumpLabel) {
    System.out.println(&quot;1&quot;);
} else if(2 == jumpLabel) {
    System.out.println(&quot;2&quot;);
} else if(3 == jumpLabel) {
    System.out.println(&quot;3&quot;);
} else if(4 == jumpLabel) {
    System.out.println(&quot;4&quot;);
}
// Removed for simplicity
else {
    System.out.println(&quot;default&quot;);
}
}
</pre>
<p>Lets see the switch functions</p>
<h3>Finite switch version</h3>
<pre class="brush: java">
public static void testSwitchFinite(int jumpLable) {

switch (jumpLable) {
case 1:
    System.out.println(&quot;1&quot;);
    break;

case 2:
    System.out.println(&quot;2&quot;);
    break;

case 3:
    System.out.println(&quot;3&quot;);
    break;

case 4:
    System.out.println(&quot;4&quot;);
    break;

case 5:
    System.out.println(&quot;5&quot;);
    break;

// Removed other cases for simplicity

default:
    System.out.println(&quot;default&quot;);
    break;
}
}
</pre>
<h3>Sparse switch version</h3>
<pre class="brush: java">
public static void testSwitchSparse(int jumpLable) {

switch (jumpLable) {
case 100:
    System.out.println(&quot;1&quot;);
    break;

case -1:
    System.out.println(&quot;2&quot;);
    break;

case 5000:
    System.out.println(&quot;3&quot;);
    break;

case -8:
    System.out.println(&quot;4&quot;);
    break;

case 1600:
    System.out.println(&quot;5&quot;);
    break;

case 250:
    System.out.println(&quot;250&quot;);
    break;

// Removed other cases for simplicity

default:
    System.out.println(&quot;default&quot;);
    break;
}
}
</pre>
<p>With the groundwork done, its the benchmarking time. The benchmarking strategy was simple. Run these functions in loop and see the result, with iteration ranging from 100 to 1000.</p>
<p>Lets look at one of the functions</p>
<pre class="brush: java">
public static void testSwitchPerf(int iteration) {
    long t1 = System.nanoTime();
    for (int i = 0; i &lt; iteration; i++) {
        testSwitchFinite(i);
    }
    long t2 = System.nanoTime();
    System.out.println(&quot;Time Taken (switch) = &quot;+(t2 - t1)/1000000);
}
</pre>
<p>Well this was the ground work, after executing the conditions, here is the data</p>
<table border="1" width="100%">
<tbody>
<tr>
<td>Iteration -&gt;</td>
<td>100</td>
<td>1000</td>
</tr>
<tr>
<td>if-else</td>
<td>8 ms</td>
<td>69 ms</td>
</tr>
<tr>
<td>switch finite</td>
<td>3 ms</td>
<td>34 ms</td>
</tr>
<tr>
<td>switch sparse</td>
<td>7 ms</td>
<td>21 ms</td>
</tr>
</tbody>
</table>
<p>NOTE: There is some difference due to the way data is provided and the sample space doesn't provide precise results. However, since the sample space is same for both, it would serve its purpose</p>
<h3>Conclusion</h3>
<p>1. There is no significant execution difference between if-else and switch. The difference observed is due to the sample space choosen.<br />
2. If using if-else, its always recommended to put frequently used if condition at the top of if-else ladder<br />
3. The finite switch statement was converted to tableswitch and sparse switch was converted to lookupswitch</p>
<p>would be interested to hear from folks about their experience in relation to this. I would say, i still prefer switch for readability. Henceforth, my review comment shall be modified as "Use switch instead of if-else, its more readable <del datetime="2009-07-28T07:33:30+00:00">and has better performance</del>"</p>
<h3>Share your thoughts</h3>
<p>I would be very keen to hear from you all, about your opinions and experience about the topic</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2009/08/if-else-vs-switch-%e2%80%93-which-is-better/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
	</channel>
</rss>

