<?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>Ashish's Tech Blog &#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, 17 Aug 2010 12:04:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<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>29</slash:comments>
		</item>
	</channel>
</rss>
