<?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; Terracotta</title>
	<atom:link href="http://www.ashishpaliwal.com/blog/category/terracotta/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>Terracotta Toolkit &#8211; Part 4 (Clustered Barrier)</title>
		<link>http://www.ashishpaliwal.com/blog/2011/02/terracotta-toolkit-part-4-clustered-barrier/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/02/terracotta-toolkit-part-4-clustered-barrier/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 08:53:05 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Clustered barrier]]></category>
		<category><![CDATA[Terracotta Toolkit]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=604</guid>
		<description><![CDATA[Recently I had a need to coordinate test drivers across JVM's, so that they all fire the load at the same time. There were many options, needed flexibility in terms that each had its own warm-up time and other dependencies. Terracotta's Clustered Barrier was a natural choice for this. Reason's were simple, I had already [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I had a need to coordinate test drivers across JVM's, so that they all fire the load at the same time. There were many options, needed flexibility in terms that each had its own warm-up time and other dependencies. Terracotta's Clustered Barrier was a natural choice for this. Reason's were simple, I had already seen it working and it was simple enough to integrate it within application.</p>
<p>What you need to run this sample<br />
1. <a href="http://www.terracotta.org/dl/?src=http://www.ashishpaliwal.com/blog">Terracotta Release Download here</a><br />
2. Include terracotta-toolkit-1.1-runtime-2.1.0.jar in classpath. You can find the jar in terracotta_install/common folder</p>
<p>The image below describes the scenario<br />
<div id="attachment_606" class="wp-caption aligncenter" style="width: 431px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/02/Toolkit.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/02/Toolkit.jpg" alt="" title="Scenario" width="421" height="403" class="size-full wp-image-606" /></a><p class="wp-caption-text">Scenario</p></div></p>
<p>Lets see how we use the Toolkit barrier to achieve this</p>
<pre class="brush: java">
public class ClusteredBarrierSample {
    static final String BARRIER_NAME = &quot;RUN_BARRIER&quot;;

    Barrier barrier;

    // Handle to the toolkit
    ClusteringToolkit clusterToolkit = null;

    public void initializeToolKit(String serverAdd, int barrierParties) {
        clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
        barrier = clusterToolkit.getBarrier(BARRIER_NAME, barrierParties);
    }

    /**
     * waits till all the parties have joined and once all drivers are ready
     * fires the test
     */
    public void fireTest() {
        try {
            barrier.await();
            // fire my network drivers
            System.out.println(&quot;firing the driver&quot;);
        } catch (Exception e) {
            e.printStackTrace();
       }
    }

    public static void main(String[] args) {
        ClusteredBarrierSample barrierSample = new ClusteredBarrierSample();
        barrierSample.initializeToolKit(args[0], Integer.parseInt(args[1]));
        barrierSample.fireTest();
    }
}
</pre>
<p>The implementation is straight simple and in 3 steps<br />
1. Intialize Terracotta Client<br />
2. Get the Barrier, with number of parties to wait for<br />
3. Call await() on the barrier</p>
<p>Using it was pretty simple and took less than 5 minutes to have the requirements met <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Next Steps:</p>
<p>Refer <a href="http://www.terracotta.org/documentation/?src=http://www.ashishpaliwal.com/blog">Terracotta Documentation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/02/terracotta-toolkit-part-4-clustered-barrier/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta Toolkit &#8211; Part 3 (Clustered Map)</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-3-clustered-map/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-3-clustered-map/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 11:40:29 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Clustered Map]]></category>
		<category><![CDATA[Terracotta Toolkit]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=532</guid>
		<description><![CDATA[Did you ever wanted to have a Map which can be clustered across JVM, without doing much work for replicating data, ensuring coherence of data? Terracotta Toolkit allows you to fullfill your dream, Use the same Map API's you have been using for long and see your data being clustered transparently with Terracotta. The fun [...]]]></description>
			<content:encoded><![CDATA[<p>Did you ever wanted to have a Map which can be clustered across JVM, without doing much work for replicating data, ensuring coherence of data? Terracotta Toolkit allows you to fullfill your dream, Use the same Map API's you have been using for long and see your data being clustered transparently with Terracotta. The fun begins, when you add new clients and they have the data with them without any additional programming.</p>
<p>Lets start with some general information about Toolkit. Refer Toolkit javadoc for more details <a href="http://www.terracotta.org/documentation" target="_blank">here</a><br />
<script type="text/javascript">// <![CDATA[
  google_ad_client = "pub-6961884887741817"; /* 468x15, created 8/2/10 */ google_ad_slot = "9956401459"; google_ad_width = 468; google_ad_height = 15;
// ]]&gt;</script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script></p>
<h2>Pre-requisite</h2>
<li>Download Terracotta 3.3.0 from <a href="http://www.terracotta.org/dl/" target="_blank">Download page</a></li>
<li>Include following <em>terracotta-toolkit-1.0-runtime-1.0.0.jar</em> into your classpath for using Toolkit. The jar is present inside Terracotta_Install_dir/common folder.</li>
<p>You can spend some time reading the following posts on Toolkit, although they can be read in any order</p>
<ul>
<li><a href="http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/" target="_blank">Getting Started with Terracotta Toolkit – Part 1</a></li>
<li><a href="http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%E2%80%93-part-2-cluster-events/" target="_blank">Getting Started with Terracotta Toolkit – Part 2 (Cluster Events)</a></li>
</ul>
<p>Lets explore a bit what do we achieve when we say Clustered Map</p>
<div id="attachment_536" class="wp-caption aligncenter" style="width: 414px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map1.png"><img class="size-full wp-image-536" title="Unclustered Map" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map1.png" alt="Unclustered Map" width="404" height="130" /></a><p class="wp-caption-text">Unclustered Map</p></div>
<p>As you can see in the figure above, we have different JVM's, each having a Map instance used by Application. Now if we were to share the same instance across app's running in different nodes, we would have to write a lot of infrastructure code to replicate data, keep data coherent etc.</p>
<div id="attachment_537" class="wp-caption aligncenter" style="width: 394px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map2.png"><img class="size-full wp-image-537" title="Clustered Map" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map2.png" alt="Clustered Map" width="384" height="137" /></a><p class="wp-caption-text">Clustered Map</p></div>
<p>The figure above depicts a Clustered Map. The Map instance is visible to App's across JVM's as if they are accessing a local instance. You can achieve this in a few lines, without worrying about the infrastructure code. Lets see how we can achieve this in few simple steps.<br />
<script type="text/javascript"><!--
google_ad_client = "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>
<h4>Steps to creare Clustered Map</h4>
<li>Initialize Toolkit</li>
<li>Get a Map reference</li>
<li>Use the Map</li>
<p><br></p>
<h3>Initializing the Toolkit</h3>
<p>Before any operations can be performed using Toolkit, it needs to be initialized first. The initialization code is very simple, just single line</p>
<pre class="brush: java">
ClusteringToolkit clustering = new TerracottaClient(&quot;localhost:9510&quot;).getToolkit();
</pre>
<p>This line initializes the Terracotta Client and gets an instance of Toolkit to work with. The argument passed to the TerracottaClient is the IP Address and Port of the Terracotta Server.</p>
<p>Have created a simple function for initialization of the Toolkit.</p>
<pre class="brush: java">
ClusteringToolkit clusterToolkit = null;

public void initializeToolKit(String serverAdd) {
clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
}
</pre>
<h3>Get/Create the Map</h3>
<pre class="brush: java">
public void initializeMap() {
    clusteredMap = clusterToolkit.getMap(MAP_NAME);
}
</pre>
<p>The code above creates a Clustered Map. There is no more infrastructure code that you have to write. This gives us a Clustered Map reference. The best part is, there are no new API's to be learned, we continue to use the same old Map API's.</p>
<p>Let's see the data class that we would share across the Map.</p>
<pre class="brush: java">
public class SharedData implements Serializable {

    private String data;

    public SharedData(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
</pre>
<p>Its a no-brainer class. Just a simple class for demonstration purpose.</p>
<p>Just to keep life simple, we are going to create a function which populates the Map, and the Nodes can then consume the populated data. Consume here would mean just call a get() and print. In real life scenario, you can mutate the data, and the updated data shall be visible across the cluster.</p>
<p>Lets see the populate function</p>
<pre class="brush: java">
protected void populateMap(int objectCount) {
        for(int i = 0; i &lt; objectCount; i++) {
            SharedData data = new SharedData(&quot;&quot;+i);
            clusteredMap.put(i, data);
        }
    }
</pre>
<p>Its a simple function which just puts the data in the Map.</p>
<p>Lets look at the consume function</p>
<pre class="brush: java">
 protected void consumeMapData(int maxObjectId) {
        Range range = new Range(1, maxObjectId);
        while(true) {
            long key = range.getRandomKey();
            byte[] dataBytes = clusteredMap.get((int)key);
            System.out.println(&quot;Key = &quot;+key);
            if(dataBytes == null) {
                System.out.println(&quot;OOPS!.. somethings wrong dude...&quot;);
                return;
            }
            SharedData data = (SharedData)deserializeObject(dataBytes);
            if(data != null) {
                System.out.println(&quot;Data = &quot;+data.getData());
            }
            try {
                // Sleep for 5 secs
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
</pre>
<p>The function just takes a random key and call a get on the map.</p>
<p>To run this implementation, we would have 3 Nodes running, 1 producer and 2 consumer. The picture below gives an idea of the topology.<br />
<div id="attachment_540" class="wp-caption aligncenter" style="width: 411px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map3.png"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map3.png" alt="Runtime Topology" title="Runtime Topology" width="401" height="130" class="size-full wp-image-540" /></a><p class="wp-caption-text">Runtime Topology</p></div></p>
<p><em>To run the implementation</em></p>
<li>Start Terracotta Server</li>
<li>Start Producer</li>
<li>Start one or more Consumer</li>
<p>You can get the complete source of the sample <a href="http://code.google.com/p/terracotta-samples/">here</a></p>
<p><script type="text/javascript"><!--
google_ad_client = "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/2010/08/getting-started-with-terracotta-toolkit-part-3-clustered-map/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta Toolkit – Part 2 (Cluster Events)</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%e2%80%93-part-2-cluster-events/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%e2%80%93-part-2-cluster-events/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 07:52:58 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Terracotta Toolkit]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=513</guid>
		<description><![CDATA[In the last post we saw Terracotta toolkit Queue. In this Part, lets explore Cluster Events. Cluster Events are propagated across the Terracotta Cluster, whenever specific event happens inside the Cluster. In this post we shall explore what are the different types of Events available. Cluster Events As of 3.3.0, following are the four Events [...]]]></description>
			<content:encoded><![CDATA[<p>In the last post we saw Terracotta toolkit Queue. In this Part, lets explore Cluster Events. Cluster Events are propagated across the Terracotta Cluster, whenever specific event happens inside the Cluster. In this post we shall explore what are the different types of Events available.</p>
<h3>Cluster Events</h3>
<p>As of 3.3.0, following are the four Events that are available</p>
<ul>
<li>Node Joined</li>
<li>Node Left</li>
<li>Operations Enabled</li>
<li>Operations Disabled</li>
</ul>
<p>So what do we need to do, in order to receive these events? Just two simple steps</p>
<ul>
<li>Implement ClusterListener</li>
<li>Register the Listener with toolkit</li>
</ul>
<h2>Pre-requisite</h2>
<li>Download Terracotta 3.3.0 from <a href="http://www.terracotta.org/dl/" target="_blank">Download page</a></li>
<li>Include following <em>terracotta-toolkit-1.0-runtime-1.0.0.jar</em> into your classpath for using Toolkit. The jar is present inside Terracotta_Install_dir/common folder.</li>
<h4>Implementing ClusterListener</h4>
<p>Here is the code</p>
<pre class="brush: java">
class MyClusterListener implements ClusterListener {

        public void nodeJoined(ClusterEvent clusterEvent) {
            try {
                System.out.println(&quot;Event Type = &quot;+clusterEvent.getType());
                System.out.println(&quot;Node Joined &quot;+clusterEvent.getNode().getId()
                        + &quot;, IP=&quot;+clusterEvent.getNode().getAddress());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        public void nodeLeft(ClusterEvent clusterEvent) {
            try {
                System.out.println(&quot;Node Left &quot;+clusterEvent.getNode().getId()
                        + &quot;, IP=&quot;+clusterEvent.getNode().getAddress());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        public void operationsEnabled(ClusterEvent clusterEvent) {
            System.out.println(&quot;Operations Enabled&quot;);
        }

        public void operationsDisabled(ClusterEvent clusterEvent) {
            System.out.println(&quot;Operations Disabled&quot;);
        }
    }
</pre>
<p>As you can see, the implementation is pretty simple. Now its time to register the listener</p>
<pre class="brush: java">
ClusterInfo clusterInfo = clusterToolkit.getClusterInfo();
clusterInfo.addClusterListener(new MyClusterListener());
</pre>
<p>Get the complete code <a href=" http://code.google.com/p/terracotta-samples/">here</a></p>
<p>Time to see the implementation in Action</p>
<ul>
<li>Start Terracotta Server</li>
<li>Start the Listener</li>
<li>Start/Stop Terracotta Clients and see the events being received</li>
</ul>
<p>There can be some innovative things that can be done inside the ClusterListener. For ex, you can send SNMP Traps to your management system for nodeJoined or nodeLeft events. </p>
<p>Stay tuned for more on Terracotta Toolkit...</p>
<p>Looking for more details, you find them here</p>
<li><a href="http://www.terracotta.org/documentation/ga/product-documentation">Terracotta Documentation</a></li>
<li><a href="http://www.terracotta.org/documentation/javadocs/terracotta-toolkit/">Terracotta Toolkit Javadoc </a></li>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%e2%80%93-part-2-cluster-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta Toolkit &#8211; Part 1</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 10:09:55 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=457</guid>
		<description><![CDATA[Terracotta Toolkit was released as part of Terracotta 3.3.0. The Toolkit is a delight for developers working on Scalable Apps, Frameworks. For more details on features of Toolkit, refer this link. In this post we shall work out a few samples using the Toolkit. We shall start with looking at Cluster Events, Clustered Queues and [...]]]></description>
			<content:encoded><![CDATA[<p>Terracotta Toolkit was released as part of Terracotta 3.3.0. The Toolkit is a delight for developers working on Scalable Apps, Frameworks. For more details on features of Toolkit, refer this <a href="http://www.terracotta.org/documentation/ga/toolkit.html#432369256_pgfId-1175126">link</a>.<br />
In this post we shall work out a few samples using the Toolkit.  We shall start with looking at Cluster Events, Clustered Queues and move to clustered Locks.</p>
<p>Lets start with some general information about Toolkit. Refer Toolkit javadoc for more details <a href="http://www.terracotta.org/documentation" target="_blank">here</a><br />
<script type="text/javascript"><!--
google_ad_client = "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></p>
<h2>Pre-requisite</h2>
<li>Download Terracotta 3.3.0 from <a href="http://www.terracotta.org/dl/" target="_blank">Download page</a></li>
<li>Include following <em>terracotta-toolkit-1.0-runtime-1.0.0.jar</em> into your classpath for using Toolkit. The jar is present inside Terracotta_Install_dir/common folder.</li>
<h2>Initializing the Toolkit</h2>
<p>Before any operations can be performed using Toolkit, it needs to be initialized first. The initialization code is very simple, just single line</p>
<pre class="brush: java">
ClusteringToolkit clustering = new TerracottaClient(&quot;localhost:9510&quot;).getToolkit();
</pre>
<p>This line initializes the Terracotta Client and gets an instance of Toolkit to work with. The argument passed to the TerracottaClient is the IP Address and Port of the Terracotta Server.</p>
<p>Have created a simple function for initialization of the Toolkit.</p>
<pre class="brush: java">
ClusteringToolkit clusterToolkit = null;

public void initializeToolKit(String serverAdd) {
clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "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></p>
<h2>Playing with Toolkit Queue</h2>
<p>Toolkit provide various Data structures that you can use, Queue being one of them.</p>
<p>Lets try and create a Producer-Consumer sample, using Toolkit Queue. Here is what we are trying to do</p>
<p><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Queue1.png"><img class="aligncenter size-medium wp-image-468" title="Queue" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Queue1-300x137.png" alt="" width="300" height="137" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "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 />
We have a producer which is going to produce some work, and the consumer shall process the work in different JVM's.</p>
<p>To achieve we need to do the following</p>
<ul>
<li>Create a Work object which shall be pushed by Producer to consumers.</li>
<li>We need to create a Producer that shall produce the work</li>
<li>We need to create a Consumer which shall consume the work. We can have multiple instances of Consumers</li>
</ul>
<p>Lets have a look at Work Object</p>
<pre class="brush: java">
class Work implements Serializable, Runnable {
private String workItem;

Work(String workItem) {
this.workItem = workItem;
}

public String getWorkItem() {
return workItem;
}

public void setWorkItem(String workItem) {
this.workItem = workItem;
}

public void run() {
System.out.println(Thread.currentThread().getName() + &quot;processing - &quot;+getWorkItem());
}
}
</pre>
<p><strong>NOTE:</strong> The Objects that shall be pushed onto the Queue should implement Serializable.</p>
<p>What we have done here. Its a very simple implementation, where we just print what the Producer pushed.<br />
Implementing Runnable is not necessary. I just added it so that I can push the work unit directly to an Executor</p>
<h3>Creating Producer</h3>
<pre class="brush: java">

static final String QUEUE_NAME = &quot;DATA_QUEUE&quot;;

public void startProducer(int capacity) {
BlockingQueue&lt;byte[]&gt; queue = clusterToolkit.getBlockingQueue(QUEUE_NAME, capacity);
System.out.println(&quot;Starting Producer....&quot;);
int i = 0;
while (i &lt; capacity) {
queue.add(serializeObject(new Work(&quot;&quot;+i++)));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</pre>
<p>Creating a clustered Queue is a one line job. We have already initialized the Toolkit, now we just call getBlockingQueue() API from the toolkit, and we get a Distributed Queue backed by Terracotta <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
After creating the Queue, we keep on adding work to the queue till its capacity is reached.</p>
<h3>Creating Consumer</h3>
<pre class="brush: java">
public void startConsumer(int capacity) {
BlockingQueue&lt;byte[]&gt; queue = clusterToolkit.getBlockingQueue(QUEUE_NAME, capacity);

// Lets add some threads to consumer
ExecutorService executors = Executors.newFixedThreadPool(5);

// a dumb way for a loop
while(true) {
try {
executors.execute((Work)deserializeObject(queue.take()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</pre>
<p>Aha! no difference in creation, the only difference is our Consumer calls take() API on the Queue to consume the work objects. Here we have a fixed size Thread pool that keep consuming the work that the producer is pushing.</p>
<p>This is it. Our implementation is complete <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  We are ready to run the sample. To execute we need to do three steps</p>
<ul>
<li>Start Terracotta Server</li>
<li>Start Producer</li>
<li>Start one or more Consumers</li>
</ul>
<p>See them in action yourself.</p>
<p>The complete code can be found at http://code.google.com/p/terracotta-samples/</p>
<p>Some ideas around what can we do with Distributed queue<br />
1. Distributed SEDA stages across JVM's<br />
2. Distributed Task processing<br />
... add your own ideas..</p>
<p>Would be interested in knowing what you do around Terracotta Toolkit Queue. Please do add comments with your implementations.</p>
<h3>What's Next?</h3>
<p>In the next post we shall be exploring more about the Cluster Events as part of Terracotta Toolkit.<br />
<script type="text/javascript"><!--
google_ad_client = "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></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Caching and Database Offloading &#8211; Best of both worlds with Terracotta Darwin Release</title>
		<link>http://www.ashishpaliwal.com/blog/2010/03/caching-and-database-offloading-best-of-both-worlds-with-terracotta-darwin-release/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/03/caching-and-database-offloading-best-of-both-worlds-with-terracotta-darwin-release/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 11:20:41 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Ehcache]]></category>
		<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Darwin]]></category>
		<category><![CDATA[Teracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=424</guid>
		<description><![CDATA[Abstract The Terracotta Darwin release a feature packed release. I love to call it a Developer's delight. Integrating Terracotta with existing apps has been simplified a lot with Express Mode. In this series we shall see some touch upon some of the new features of the Darwin release How is this post organized? We shall [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Abstract</strong></p>
<p>The <a href="http://www.terracotta.org/start/?src=darwin-release-badge">Terracotta Darwin release</a> a feature packed release. I love to call it a Developer's delight. Integrating Terracotta with existing apps has been simplified a lot with Express Mode. In this series we shall see some touch upon some of the new features of the Darwin release</p>
<p><strong>How is this post organized?</strong></p>
<p>We shall take a sample Use Case(s), and discuss the needs. Using the Use Case we shall see the fitment of Terracotta features. Discussion will be around the following</p>
<ul>
<li>Bulk Loading to Cache</li>
<li>Write Behind Cache</li>
</ul>
<p><strong>The Use Case - Bulk Loading</strong></p>
<p>Bulk loading the cache is a common need for Cache warmup. Here we try to load the data into Cache in a single go, rather then on Cache miss. This help us in reducing the database lookup upon each miss.</p>
<p><em><strong>Some Use Cases</strong</em><br />
<strong>Case 1:</strong> For a Catalogue site, loading all the available catalogues/Products during startup</p>
<p><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/03/catalogue_use_case-300x100.png" alt="catalogue_use_case" title="catalogue_use_case" width="300" height="100" class="aligncenter size-medium wp-image-445" /><br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>The cache can be loaded at the startup with the hot set o Products or as desired, against loading it at runtime, upon a Cache miss.</p>
<p><strong>Case 2:</strong> For an Element Management System, loading all the Managed Devices into cache, available to all nodes in the cluster</p>
<p><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/03/ems_use_case-300x152.png" alt="ems_use_case" title="ems_use_case" width="300" height="152" class="aligncenter size-medium wp-image-446" /><br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>For an EMS Device Information for the Devices it is managing is used most often. The Device info can be bulk loaded at the startup. The example show the use of cache by a Poller, which Polls the Device status.</p>
<p>There are other common use cases. Please add comment with your Use case.</p>
<p><strong>Ehcache Bulk Loading with Terracotta</strong></p>
<p><a href="http://www.terracotta.org/start/?src=darwin-release-badge">Terracotta Darwin release</a> has optimized bulk loading in Ehcache. In normal scenario, loading elements in Ehcache, would update the cache entry to all the clustered caches, making the bulk loading a bit slower.</p>
<p>Let's see how bulk loading in action</p>
<pre class="brush: java">
      // Get the Cache to be preloaded
      Cache ehcache = CacheManager.getInstance().getCache(&quot;mycache&quot;);

      // Set this property before bulk loading
      ehcache.setNodeCoherence(false);

      // Load everything here
      loadCache(); 

      // reset the property
      ehcache.setNodeCoherence(true);

      // Wait for all data to be distributed across cluster
      ehcache.waitUntilClusterCoherent();
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>What's being done inside the loadCache()?<br />
Here is a glimpse</p>
<pre class="brush: java">
private void loadCache() {
   // Query the DB get the data and get the result into array
   // or what ever data structure you need

   // iterate over result and put into cache
   for(int i = 0; i &lt; data.length; i++) {
       Element element = new Element(data.getId, data);
       ehcache.put(element);
   }
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>Here is how the cache look when we are bulk loading the data. We are using both nodes to load distinct data to speed up loading process. The loading can be taken care by a single node also.</p>
<p><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/03/ehcache_-_while_bulk_loading-300x198.png" alt="ehcache - While Bulk uploading" title="ehcache - While Bulk uploading" width="300" height="198" class="aligncenter size-medium wp-image-441" /></p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>Once the bulk loading is completed, and Nodes are set to coherent again, the data is replicated across the cluster, and all Nodes have the same data set.</p>
<p><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/03/ehcache_-_after_bulk_loading-1-300x208.png" alt="ehcache - After Bulk upload" title="ehcache - After Bulk upload" width="300" height="208" class="aligncenter size-medium wp-image-442" /></p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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><strong>What's Next?</strong><br />
In the next post we shall cover the Write-Behind feature of Ehcache for DB offloading. I will rewrite the code of one my previous post <a href="http://www.ashishpaliwal.com/blog/2010/01/demystifying-terracotta-tim-async-scalable-way-to-off-load-db-updates-from-app-transaction/">Exploring Terracotta tim-async - Scalable way to off-load DB updates from App Transaction</a>, to use the write-behind feature.</p>
<p><script type="text/javascript"><!--
google_ad_client = "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/2010/03/caching-and-database-offloading-best-of-both-worlds-with-terracotta-darwin-release/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>So you want Distributed, Scalable and Highly Available Cache?</title>
		<link>http://www.ashishpaliwal.com/blog/2010/02/so-you-want-distributed-scalable-and-highly-available-cache/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/02/so-you-want-distributed-scalable-and-highly-available-cache/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 09:22:53 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Ehcache]]></category>
		<category><![CDATA[Terracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=402</guid>
		<description><![CDATA[Abstract So you want Distributed, Scalable and Highly Available Cache? If yes, then this is the right place for you. The Terracotta Ehcache release has these features inbuilt. The Express Installation mode has simplified Terracotta integration in your application. How this post is organized First we shall start with simple standalone cache and then see [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Abstract</strong></p>
<p><em><strong>So you want Distributed, Scalable and Highly Available Cache?</strong></em> If yes, then this is the right place for you. The Terracotta Ehcache release has these features inbuilt. The <a href="http://www.terracotta.org/documentation/ga/product-documentation-2.html#382351408_pgfId-11318">Express Installation</a> mode has simplified Terracotta integration in your application. </p>
<p><strong>How this post is organized</strong><br />
First we shall start with simple standalone cache and then see how Terracotta can easily help us create a Distributed, Scalable and Highly Available cache, with a few minor configurations</p>
<p><strong>What all do you need run the example?</strong></p>
<ul>
<li>Terracotta 3.2.0 - Download it from <a href="http://www.terracotta.org/dl/">here</a></li>
</ul>
<p><script type="text/javascript"><!--
google_ad_client = "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><strong>Sample Application</strong><br />
Lets design a sample application (a real simple one), which we shall use to demonstrate the features. Device Monitoring is a common requirement in OSS System, and caching the Device information reduces the Database hits. The essential components of our application are<br />
- DevideInfo - A POJO that stores device information<br />
- CacheHandler - Class that handles cache initialization and other ops</p>
<p>Lets see the CacheHandler class, which is the heart of our implementation</p>
<pre class="brush: java">
public class DeviceInfo  implements Serializable {

    String deviceId;

    String name;

    // .... other device information

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
}
</pre>
<p>The class is simple and contains information related to the device.</p>
<p>Let see our CacheHandler class</p>
<pre class="brush: java">
public class CacheHandler {

    public Cache deviceCache;

    public void initCache() {
        // Initialize the CacheManager
        CacheManager cacheManager = CacheManager.create();
        // Get the Cache to store device information
        deviceCache = cacheManager.getCache(&quot;deviceCache&quot;);
    }

    public void addToCache(DeviceInfo device) {
        Element el = new Element(device.getDeviceId(), device);
        deviceCache.put(el);
    }

    protected int getDeviceCacheSize() {
        return deviceCache.getSize();
    }

    public static void main(String[] args) {
        CacheHandler handler = new CacheHandler();
        handler.initCache();

        // Lets add 10 devices
        // just to keep life simple
        for(int i = 0; i &lt; 10; i++) {
            DeviceInfo device = new DeviceInfo();
            device.setDeviceId(&quot;Device-&quot;+i);
            handler.addToCache(device);
        }

        // Not recommended in production
        System.out.println(&quot;Cache Size = &quot;+handler.getDeviceCacheSize());

    }
}
</pre>
<p>The class has two main functions<br />
- initCache - The API initializes the cache<br />
- addToCache - The API adds the device information to the device cache</p>
<p>Lets see our ehcache.xml</p>
<pre class="brush: xml">
&lt;ehcache xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:noNamespaceSchemaLocation=&quot;ehcache.xsd&quot;
             updateCheck=&quot;true&quot; monitoring=&quot;autodetect&quot;&gt;

   &lt;defaultCache
            maxElementsInMemory=&quot;10000&quot;
            eternal=&quot;false&quot;
            timeToIdleSeconds=&quot;120&quot;
            timeToLiveSeconds=&quot;120&quot;
            overflowToDisk=&quot;true&quot;
            diskSpoolBufferSizeMB=&quot;30&quot;
            maxElementsOnDisk=&quot;10000000&quot;
            diskPersistent=&quot;false&quot;
            diskExpiryThreadIntervalSeconds=&quot;120&quot;
            memoryStoreEvictionPolicy=&quot;LRU&quot;
            /&gt;

    &lt;cache name=&quot;deviceCache&quot;
           maxElementsInMemory=&quot;1000000&quot;
           maxElementsOnDisk=&quot;1000&quot;
           eternal=&quot;false&quot;
           overflowToDisk=&quot;false&quot;
           diskSpoolBufferSizeMB=&quot;20&quot;
           timeToIdleSeconds=&quot;100&quot;
           timeToLiveSeconds=&quot;100&quot;
           memoryStoreEvictionPolicy=&quot;LFU&quot;&gt;
     &lt;/cache&gt;

&lt;/ehcache&gt;
</pre>
<p>In the configuration we have defined a deviceCache, that we shall use to store device information.</p>
<p>Following is the list of jars you would need to run this app </p>
<ul>
<li>ehcache-core-1.7.2.jar</li>
<li>slf4j-api-1.5.8.jar</li>
<li>slf4j-jdk14-1.5.8.jar</li>
</ul>
<p>All these jars are available as part of Terracotta installation under <TC Install Dir>/distributed-cache directory</p>
<p>You can run this example and see the same in action.</p>
<p><script type="text/javascript"><!--
google_ad_client = "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>
<p><strong>Making it Distributed....</strong></p>
<p>Now lets assume that we want to make the Cache fault tolerant, survive JVM crashes, as well as have it available on different JVM's. It should be able to Scale as we add more JVM's to it and other stuff. With Terracotta, we can just do it in a few steps without changing the code. the magic lies with Express Installation mode, introduced in Terracotta version 3.2.0 and above</p>
<p>Lets see the 3 steps that we need to perform</p>
<p>1. Updates to the ehcache.xml<br />
Add following element to ehcache.xml</p>
<p>&lt;terracottaConfig url=&quot;localhost:9510&quot; /&gt;</p>
<p>and for the deviceCache, we add &lt;terracotta /&gt; element</p>
<p>here is the updated ehcache.xml</p>
<pre class="brush: xml">
&lt;ehcache xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:noNamespaceSchemaLocation=&quot;ehcache.xsd&quot;
             updateCheck=&quot;true&quot; monitoring=&quot;autodetect&quot;&gt;

   &lt;terracottaConfig url=&quot;localhost:9510&quot; /&gt; 

   &lt;defaultCache
            maxElementsInMemory=&quot;10000&quot;
            eternal=&quot;false&quot;
            timeToIdleSeconds=&quot;120&quot;
            timeToLiveSeconds=&quot;120&quot;
            overflowToDisk=&quot;true&quot;
            diskSpoolBufferSizeMB=&quot;30&quot;
            maxElementsOnDisk=&quot;10000000&quot;
            diskPersistent=&quot;false&quot;
            diskExpiryThreadIntervalSeconds=&quot;120&quot;
            memoryStoreEvictionPolicy=&quot;LRU&quot;
            /&gt;

    &lt;cache name=&quot;deviceCache&quot;
           maxElementsInMemory=&quot;1000000&quot;
           maxElementsOnDisk=&quot;1000&quot;
           eternal=&quot;false&quot;
           timeToIdleSeconds=&quot;100&quot;
           timeToLiveSeconds=&quot;100&quot;
           memoryStoreEvictionPolicy=&quot;LFU&quot;&gt;

        &lt;terracotta /&gt;
     &lt;/cache&gt;

&lt;/ehcache&gt;
</pre>
<p>There is no need to change the code <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>2. Add ehcache-terracotta-1.8.0.jar to the classpath</p>
<p>Lets start the Terracotta Server</p>
<p>3. Goto Terracotta_Install_dir/bin and execute </p>
<blockquote><p>$ ./start-tc-server.sh</p></blockquote>
<p>This shall start the Terracotta server</p>
<p>Now run the application on multiple JVM's. The device information is available on all client JVM's <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>To monitor Cache, you can use <a href="http://www.terracotta.org/confluence/display/docs/Terracotta+Developer+Console">Terracotta Dev Console</a></p>
<p>If you have further question/queries, please visit <a href="http://forums.terracotta.org/forums/forums/list.page">Terracotta Forums</a>.</p>
<p><strong>What's coming up Next</strong>?<br />
The next post shall touch on write-behind feature in the latest <a href="http://www.terracotta.org/beta/darwin">Terracotta Darwin</a> release. Its essentially to get best of both worlds - Caching and Database Offloading <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Stay tuned..</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 300x250, created 2/9/10 */
google_ad_slot = "1177095982";
google_ad_width = 300;
google_ad_height = 250;
//-->
</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/2010/02/so-you-want-distributed-scalable-and-highly-available-cache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exploring Terracotta tim-async &#8211; Scalable way to off-load DB updates from App Transaction</title>
		<link>http://www.ashishpaliwal.com/blog/2010/01/demystifying-terracotta-tim-async-scalable-way-to-off-load-db-updates-from-app-transaction/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/01/demystifying-terracotta-tim-async-scalable-way-to-off-load-db-updates-from-app-transaction/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 14:59:15 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=373</guid>
		<description><![CDATA[Lets start this chat with a small conversation Manager: What are the options we have to increase the TPS of our SMSC Server? Architect: Can you elaborate a bit on this? Manager: As of now we process a request and update the Database in the same tranaction. Essentially, we are operating our Server at the TPS at [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>Lets start this chat with a small conversation</p>
<p><strong>Manager:</strong> What are the options we have to increase the TPS of our <a href="http://en.wikipedia.org/wiki/SMSC">SMSC</a> Server?</p>
<p><strong>Architect:</strong> Can you elaborate a bit on this?</p>
<p><strong>Manager:</strong> As of now we process a request and update the Database in the same tranaction. Essentially, we are operating our Server at the TPS at which our DB can operate.</p>
<p><strong>Architect:</strong> Well we have to ensure that our Data is persisted</p>
<p><strong>Manager:</strong> Yes, but can't we update the DB asynchronously, without lossing data</p>
<p><strong>Architect:</strong> Yes it can be done, but we have to create a lot of infrastructure code around this, so that we don't loose data for failed transaction, process crashes etc.</p>
<p>If you have been in such a situation, the post is meant for you.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>
<h2>Summary</h2>
<p><strong><em>For any request, don't update the Database in same transaction, but data need to be persisted</em></strong>. This has always been a typical need to increase the liveliness of the application. The application accessing data in memory work must faster, than fetching/updating data form databases. Assume you have a solution which helps you to work in memory and allows your application to update the data to Datastore in separate transaction, providing HA and Scalability out of the box. If this is what you are looking at, Terracotta async processor (tim-async) is the right fit for you.</p>
<p>The article is organized to detail what tim-async is, followed by a sample application.</p>
<p>We shall see tim async in brief and then later would walk through the a small POC that I build around the same.</p>
<h2>Pre-requisite</h2>
<p>You should have basic understanding of Terracotta 3.2 and its Configuration.<br />
You need to download tim-async using tim-get tool</p>
<h2>What is tim-async?</h2>
<p><strong><em>tim</em></strong> stands for <strong><em>Terracotta Integration Module</em></strong>, and <strong><em>tim-async</em></strong> is module for asynchronous processing. tim-async provides a scalable, high performance way to asynchronously write the business data to data source (typically a database), while the application works on in-memory data structures. Decoupling the main processing from the underlying database decreases the write latency of domain objects, while high availability of data is provided by terracotta.</p>
<h3>What features does it have</h3>
<ul>
<li>Multithreaded write behind to flush the processed data from the client VMs (L1s) to the data source</li>
<li>Data to be flushed remains highly available (HA) as it is shared with terracotta.</li>
<li>Every client takes the responsibility of writing its data set to the data source</li>
<li>Listeners to monitor work progress at bucket level.</li>
</ul>
<p>NOTE: Have pulled out this information from the attachment <a href="http://www.terracotta.org/confluence/display/wiki/Notes+on+Tim-Async">here</a></p>
<h3>Building Blocks of tim-async from User Perspective</h3>
<p>From a User's POV, these three are the important building blocks</p>
<ul>
<li>ItemProcessor</li>
<li>AsyncCoordinator</li>
<li>AsyncConfig</li>
</ul>
<p>These are all classes/interface that are part of tim-async. Lets look at them in brief</p>
<h3>ItemProcessor</h3>
<p>Its an interface and the implementation class of this interface is where we shall be writing the actual processing logic of the Domain Object, like persisting it to the DB.</p>
<pre class="brush: java">
public interface ItemProcessor&lt;I&gt; {
public void process(I item) throws ProcessingException;
}
</pre>
<h3>AsyncCoordinator</h3>
<p>Its a core class and need to be declared as Shared Root in tc-config.xml. It allows work to be added and processed asynchronously.<br />
The class has a method start() that needs to be called by every client node (Terracotta L1) to participate in processing.<br />
An ItemProcessor instance is local to the node, so its the right place to hold stuff DB Connection etc</p>
<h3>AsyncConfig</h3>
<p>Its an interface and can be implemented to custom tailor the configuration of Async processing. If we don't define one, the org.terracotta.modules.async.configs.DefaultAsyncConfig is used.</p>
<pre class="brush: java">
public interface AsyncConfig {
public long getWorkDelay();

public long getMaxAllowedFallBehind();

public boolean isStealingEnabled();
}
</pre>
<p>Now lets see how can we implement tim-async in our application (We shall see the sample application)</p>
<p>- We need to implement ItemProcessor for doing custom processing say for example putting the stuff in DB<br />
- We need to initialize AsyncCoordinator and call start() API, pass on the ItemProcessor from previous step as a param.<br />
- Create tc-config.xml (pick teh sample from tim-async example), add the AsyncCoordinator field instance as the root<br />
- Start TC Server and Client JVM's with tc-config.xml created above<br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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 />
Lets see these steps in Action.</p>
<h2>Sample Application</h2>
<p>I had written a SMSC simulator based on jsmpp which used to receive the SubmitSM request from Client, used to persist in the DB and return<br />
the id to the client. There is a specific reason why I choose this application. I already had this running and since the SubmitSM just needed to persisted in DB for subsequent processing by other process. The business case was justified that the Server is very responsive to Client, as well as its ensured that the Data is persisted.</p>
<p>Lets walk through the a simple processing sequence</p>
<ul>
<li>Client send a SubmitSM request</li>
<li>Server translated it into an internal SMS POJO, assigns a unique ID to the SMS</li>
<li>Server persists the SMS in Database</li>
<li>Sever sends the ID generate as part of SubmitSM response</li>
</ul>
<p><em>The application uses Hibernate to save the POJO in MySQL Database</em>.</p>
<p>Since the Domain object is least significant so won't discuss the internals of SMS POJO</p>
<p>Lets see how we enhanced the application to asynchronously update the DB</p>
<h3>Implementing the ItemProcessor</h3>
<pre class="brush: java">
public class AsyncSMSProcessor implements ItemProcessor {
public void process(final SMS sms) throws ProcessingException {
Session hibernateSession = DAO.getSession();
DAO.getSession().getTransaction().begin();
DAO.getSession().save(sms);
DAO.getSession().getTransaction().commit();
}
}
</pre>
<p>Essentially what we have to write the logic of saving the SMS object to the database. This is the object that Terracotta is going to pass back to us.<br />
What we do here is save the SMS in a Hibernate transaction. This completes out ItemProcessor code</p>
<h3>Initialize AsyncCoordinator</h3>
<pre class="brush: java">
public class SMSProcessor {

public AsyncCoordinator asyncUpdator;

public SMSProcessor() {
asyncUpdator = new AsyncCoordinator();
// Use the default API

asyncUpdator.start(new AsyncSMSProcessor());

}

}
</pre>
<pre class="brush: java">
public long processIncomingSMS(SubmitSm submitSm,
SMPPServerSession source, ...) {

// some logic here
// give the date to AsyncCoordinator
asyncUpdator.add(sms);
// some logic there

}
</pre>
<p>This is the change that we have done here. Earlier we used to save the SMS in DB here. We have now given the data to AsyncCoordinator for subsequent processing.</p>
<p>Let's look at the tc-config.xml</p>
<p>this is what we need to add to the tc-config.xml</p>
<pre class="brush: xml">
&lt;application&gt;
&lt;dso&gt;
&lt;!--Declaring a field of a class a root will make it available for all instances
of our app that runs via DSO--&gt;
&lt;roots&gt;
&lt;!-- XXX: --&gt;
&lt;root&gt;
&lt;field-name&gt;com.tc.timasync.demo.smsAsyncCoordinator&lt;/field-name&gt;
&lt;/root&gt;
&lt;/roots&gt;
&lt;/dso&gt;
&lt;/application&gt;
</pre>
<p>We declared the AsyncCoordinator variable as DSO root here, which makes it shared across cluster.</p>
<p>That's it.</p>
<p>We are ready. Now we start Terracotta server with our tc-config file and start our SMSC Simulator as TC Client.</p>
<h3>How does it all fit together</h3>
<p>As we see the instead of updating the DB in the same transaction, we handed the data over to Terracotta. Essentially, this meant that our data has gone to Server, and won't be lost against crashes. The application operated at memory speed and responded to client. The Terracotta Server based on the configuration of tim-async shall call the ItemProcessor in different transaction. We can have multiple nodes updating the DB asynchronously or some other way, based upon the Use Case.</p>
<p>Let's run the both the implementations</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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><strong>Note on Comparison of both the implementations</strong></p>
<p>I shall run both the implementation on the same hardware/OS, which would be my Laptop with 2GB of RAM, runnning Windows and MYSQL 5.X. The comparison shall be relative for the two implementation approached, and not the absolute figures. The figures would be much better if the samples are run on higher end machined with Terracotta Server (L2) running on a dedicated machine and the Clients (L1) running on different machines. The idea here is just to see the TPS of the Server.</p>
<h3>Case I: DB updates in App transaction</h3>
<p>For 10 runs of sending 1000 SubmitSM request client took following time</p>
<p>Total Time for 1000 SMS = 28891<br />
Total Time for 1000 SMS = 34234<br />
Total Time for 1000 SMS = 27812<br />
Total Time for 1000 SMS = 34547<br />
Total Time for 1000 SMS = 29953<br />
Total Time for 1000 SMS = 34344<br />
Total Time for 1000 SMS = 33985<br />
Total Time for 1000 SMS = 35328<br />
Total Time for 1000 SMS = 36968</p>
<h3>Case II: DB updates based on tim-async</h3>
<p>Total Time for 1000 SMS = 1359<br />
Total Time for 1000 SMS = 1125<br />
Total Time for 1000 SMS = 781<br />
Total Time for 1000 SMS = 813<br />
Total Time for 1000 SMS = 750<br />
Total Time for 1000 SMS = 719<br />
Total Time for 1000 SMS = 703<br />
Total Time for 1000 SMS = 719<br />
Total Time for 1000 SMS = 718<br />
Total Time for 1000 SMS = 735</p>
<p>There was a significant decrease in the processing time of request <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>What's next</h2>
<p>Download Terracotta from <a href="http://www.terracotta.org/dl/">here</a> and try yourself. You can also <a href="http://www.terracotta.org/beta/darwin">register for upcoming Darwin release</a>, which has many new interesting features</p>
<p><strong>Resources</strong></p>
<ul>
<li>http://blog.terracottatech.com/2009/02/offloading_a_db_even_when_upda.html - A wonderful post by Ari</li>
<li>http://www.slideshare.net/sbtourist/real-terracotta-presentation</li>
<li>http://forums.terracotta.org/forums/forums/list.page</li>
</ul>
</div>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 1/25/10 */
google_ad_slot = "2118617107";
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>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/01/demystifying-terracotta-tim-async-scalable-way-to-off-load-db-updates-from-app-transaction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Essential Components of Terracotta based Application</title>
		<link>http://www.ashishpaliwal.com/blog/2009/11/essential-components-of-terracotta-based-application/</link>
		<comments>http://www.ashishpaliwal.com/blog/2009/11/essential-components-of-terracotta-based-application/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 07:40:23 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=353</guid>
		<description><![CDATA[Abstract How does a Terracotta Application look like? What are the essential components that make up the application? These were the question I had after writing my first post “Getting Started with Terracotta”. Here I try to take a quick look at these questions from a Users point of view. Please note that this post [...]]]></description>
			<content:encoded><![CDATA[<h2>Abstract</h2>
<p>How does a <a href="http://www.terracotta.org/" target="_blank">Terracotta</a> Application look like? What are the essential components that make up the application? These were the question I had after writing my first post “<a href="http://www.ashishpaliwal.com/blog/2009/11/getting-started-with-terracotta/" target="_blank">Getting Started with Terracotta</a>”. Here I try to take a quick look at these questions from a Users point of view. Please note that this post doesn’t try to dive deep into Terracotta inner working.</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 728x15, created 11/25/09 */
google_ad_slot = "8166984671";
google_ad_width = 728;
google_ad_height = 15;
// --></script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script></p>
<div id="attachment_355" class="wp-caption aligncenter" style="width: 310px"><img class="size-medium wp-image-355" title="tc_app_comps" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2009/11/tc_app_comps-300x207.png" alt="Components of Terracotta based Application" width="300" height="207" /><p class="wp-caption-text">Components of Terracotta based Application</p></div>
<p>To keep life simple, have considered the general application architecture, which essentially can be any Terracotta app. From the figure we can see that we have four different parts that contribute to a complete Terracotta app.  </p>
<p><strong> User Application</strong> – These are applications that want to use Terracotta to Scale. They can either use Terracotta transparently or can use explicit Terracotta API’s  </p>
<p><strong> Terracotta Server</strong> – It’s the nerve center. Terracotta applications can’t run without it. For running any TC application, it’s a must to run atleast one TC Server.  </p>
<p><strong> Terracotta config file</strong> – Also known as tc-config.xml (default name). It provides the detailed configuration for Server as well as Client. It contains information like Server’s IP’s,  persistence mode, classes to instrument etc. </p>
<p><strong>Terracotta Libraries</strong> – These are essentially part of Client or User applications. They are the work horses of the running application and enables Terracotta integration with User application. An example would be dso-java.bat script adds the Terracotta bootjars to the classpath, enabling Terracotta features for the application.  </p>
<p>So how does it all fit together at runtime</p>
<ul>
<li>Start Terracotta Server, providing a configuration file with desired configuration</li>
<li>Start User Application using dso-java.(bat|sh) instead of normal java, along with a configuration file</li>
<li>That’s it <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
</ul>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 728x15, created 11/25/09 */
google_ad_slot = "8166984671";
google_ad_width = 728;
google_ad_height = 15;
// --></script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2009/11/essential-components-of-terracotta-based-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

