<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>My Technology blog...</title>
	<atom:link href="http://tsjblog.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://tsjblog.wordpress.com</link>
	<description>Juicy Java Tidbits picked up from everywhere</description>
	<lastBuildDate>Thu, 30 Aug 2007 18:37:09 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='tsjblog.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/871384574f2b03e6b7b26178e47d2121?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>My Technology blog...</title>
		<link>http://tsjblog.wordpress.com</link>
	</image>
			<item>
		<title>An Aside : A useful database question&#8230;</title>
		<link>http://tsjblog.wordpress.com/2007/08/30/an-aside-a-useful-database-question/</link>
		<comments>http://tsjblog.wordpress.com/2007/08/30/an-aside-a-useful-database-question/#comments</comments>
		<pubDate>Thu, 30 Aug 2007 18:37:09 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Database Delete]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/08/30/an-aside-a-useful-database-question/</guid>
		<description><![CDATA[Delete Duplicate Rows From an Oracle Table
An easy way to remove the duplicate rows before the primary key or unique indexes can be created:

DELETE FROM table_name
WHERE rowid not in
(SELECT MIN(rowid)
FROM table_name
GROUP BY column1, column2, column3... ;
The GROUP BY is used on the columns that make the primary key for the table. This query deletes each [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=18&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="font-family:Arial,Helvetica,Sans-Serif;font-size:18px;font-weight:bold;color:#ff6600;margin-left:10px;margin-top:10px;">Delete Duplicate Rows From an Oracle Table</p>
<p>An easy way to remove the duplicate rows before the primary key or unique indexes can be created:</p>
<pre><code>
DELETE FROM table_name
WHERE rowid not in
(SELECT MIN(rowid)
FROM table_name
GROUP BY column1, column2, column3... ;</code></pre>
<p>The GROUP BY is used on the columns that make the primary key for the table. This query deletes each row in the group after the first row.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/18/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/18/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=18&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/08/30/an-aside-a-useful-database-question/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Java generics simplified</title>
		<link>http://tsjblog.wordpress.com/2007/08/24/java-generics-simplified/</link>
		<comments>http://tsjblog.wordpress.com/2007/08/24/java-generics-simplified/#comments</comments>
		<pubDate>Fri, 24 Aug 2007 23:52:30 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Collections]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Collections]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/08/24/java-generics-simplified/</guid>
		<description><![CDATA[Java generics. Much talked about these days. So lets take a look at what generics means. Anyone who has use java has come across the java Collections Framework.Very convenient, fun to use pass around , manipulate play with and all that. Except for one little detail So far you could add objects of any type [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=20&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p align="justify"><font color="#000000"><font face="Verdana" size="2">Java generics. Much talked about these days. So lets take a look at what generics means. Anyone who has use java has come across the java Collections Framework.Very convenient, fun to use pass around , manipulate play with and all that. Except for one little detail So far you could add objects of any type into a collection. For example:</font></font><font color="#000000"><font face="Verdana" size="2">import java.util.List;</font></font><br />
<font color="#000000"><font face="Verdana" size="2">import java.util.ArrayList;</font></font></p>
<p><font color="#000000"><font face="Verdana" size="2">List guestList = new ArrayList();</font></font><br />
<font color="#000000"><font face="Verdana" size="2">personList.add(&#8220;Tshah&#8221;);</font></font><br />
<font color="#000000"><font face="Verdana" size="2">personList.add(new Integer(10));</font></font></p>
<p><font color="#000000"><font face="Verdana" size="2">And my code will happily compile and add the two objects in. Except, this brings two major issues to the fore:</font></font></p>
<p><font color="#000000"><font face="Verdana" size="2">1. Java collections so far lacked any type-checking unless you implemented it manually.</font></font><br />
<font color="#000000"><font face="Verdana" size="2">2. When you access a collection element, things could go horribly wrong unless you knew which class to typecast the collection element to, causing a ton of possible runtime errors.</font></font></p>
<p><font color="#000000"><font face="Verdana" size="2"> </font></font></p>
<p align="justify"><font color="#000000"><font face="Verdana" size="2">Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked.  Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection. The compiler can now verify at compile time that the type constraints are not violated at run time, thereby guaranteeing more robustness. </font></font></p>
<p><font color="#000000"><font face="Verdana" size="2"><br />
The main difference in the two methodologies is that while in the first case the code and the compiler tell us what the developer &#8220;thinks&#8221; is true at a given point of execution in the code(which the VM checks only at run-time) versus, what a compiler &#8220;knows&#8221; and has &#8220;verified&#8221; to be true at the same given point in time.<br />
</font></font></p>
<p><font color="#000000"><font face="Verdana" size="2"> </font></font></p>
<p align="justify"><font color="#000000"><font face="Verdana" size="2">While the primary use of generics is collections, there are many other uses. “Holder classes,” such as WeakReference and ThreadLocal, have all been generified, that is, they have been retrofitted to make use of generics. More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information.</font></font><font color="#000000"><font face="Verdana" size="2">Generics are implemented by <em>type erasure</em>: generic type information is present only at compile time, after which it is <em>erased</em> by the compiler. This is necessary to achieve total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as <em>raw</em> types). Doing so would however imply that parameter type information is not available at run time, meaning the new automatically generated casts may fail when interoperating with ill-behaved legacy code(One is type-checked the other is not, imagine what happens when the types dont match up?). There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.  </font></font></p>
<p><font color="#000000"><font face="Verdana" size="2">This problem has been solved by adding wrapper classes to <code>java.util.Collections</code> which allow us to &#8220;wrap&#8221; a collection in a type-safe class  and thereby provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers.  </font></font></p>
<p><font color="#000000"><font face="Verdana" size="2">Suppose you have a set of strings, <code>s</code>, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to <code>String</code> fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:  </font></font></p>
<pre><font color="#000000"><font face="Verdana" size="2">    Set&lt;String&gt; s = new HashSet&lt;String&gt;();
</font></font></pre>
<p><font color="#000000"><font face="Verdana" size="2"> with this declaration: </font></font></p>
<pre><font color="#000000"><font face="Verdana" size="2">    Set&lt;String&gt; s = Collections.checkedSet(new HashSet&lt;String&gt;(), String.class);
</font></font></pre>
<p><font color="#000000"><font face="Verdana" size="2">  the collection will throw a <code>ClassCastException</code> at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem.  Meaning, we have now implemented type checking at the point-of-entry for previously unchecked code! </font></font></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/20/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/20/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/20/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=20&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/08/24/java-generics-simplified/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Java Sizeof()</title>
		<link>http://tsjblog.wordpress.com/2007/08/11/java-sizeof/</link>
		<comments>http://tsjblog.wordpress.com/2007/08/11/java-sizeof/#comments</comments>
		<pubDate>Sat, 11 Aug 2007 22:46:03 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/08/11/java-sizeof/</guid>
		<description><![CDATA[Java of course doesnt have a sizeof method for objects. So then how do we measure the size of a Java object in the system?
Method 1: Serialize the object and measure the size of the byte stream. 
Problem: But that would not work because objects are not the same size when they are resident in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=19&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><div align="justify">Java of course doesnt have a sizeof method for objects. So then how do we measure the size of a Java object in the system?</p>
<p><strong>Method 1:</strong> Serialize the object and measure the size of the byte stream. <br />
<strong>Problem:</strong> But that would not work because objects are not the same size when they are resident in the JVM and when they are serialized. The way the objects are encoded changes the actual size of the object. <br />
Example: Strings. Every character is two bytes in memory and lesser than that when the object is encoded using the UTF-8 encoding format before serialization.<br />
<b><br />
Method 2:</b> Create a large number of identical class instances and carefully measure the resulting increase in the JVM used heap size.</p>
<p><strong>Method 3:</strong> An object instance can be (approximately) sized by totaling all of its non-static data fields (remember to include fields defined in the superclass). Class super interfaces have no impact on the&nbsp; object  size. the full object size can be obtained as a closure over the entire object graph rooted at the starting object.</p>
<p>// java.lang.Object shell size in bytes:<br />
&nbsp;&nbsp;&nbsp; public static final int OBJECT_SHELL_SIZE&nbsp;&nbsp; = 8;<br />
&nbsp;&nbsp;&nbsp; public static final int OBJREF_SIZE&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = 4;<br />
&nbsp;&nbsp;&nbsp; public static final int LONG_FIELD_SIZE&nbsp;&nbsp;&nbsp;&nbsp; = 8;<br />
&nbsp;&nbsp;&nbsp; public static final int INT_FIELD_SIZE&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = 4;<br />
&nbsp;&nbsp;&nbsp; public static final int SHORT_FIELD_SIZE&nbsp;&nbsp;&nbsp; = 2;<br />
&nbsp;&nbsp;&nbsp; public static final int CHAR_FIELD_SIZE&nbsp;&nbsp;&nbsp;&nbsp; = 2;<br />
&nbsp;&nbsp;&nbsp; public static final int BYTE_FIELD_SIZE&nbsp;&nbsp;&nbsp;&nbsp; = 1;<br />
&nbsp;&nbsp;&nbsp; public static final int BOOLEAN_FIELD_SIZE&nbsp; = 1;<br />
&nbsp;&nbsp;&nbsp; public static final int DOUBLE_FIELD_SIZE&nbsp;&nbsp; = 8;<br />
&nbsp;&nbsp;&nbsp; public static final int FLOAT_FIELD_SIZE&nbsp;&nbsp;&nbsp; = 4;
</div>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/19/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/19/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/19/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=19&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/08/11/java-sizeof/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Next most important thread lesson &#8211; Synchronisation.</title>
		<link>http://tsjblog.wordpress.com/2007/08/03/next-most-important-thread-lesson-synchronisation/</link>
		<comments>http://tsjblog.wordpress.com/2007/08/03/next-most-important-thread-lesson-synchronisation/#comments</comments>
		<pubDate>Fri, 03 Aug 2007 21:09:54 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Multi-threading]]></category>
		<category><![CDATA[Java Threads]]></category>
		<category><![CDATA[Synchronisation]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/08/03/next-most-important-thread-lesson-synchronisation/</guid>
		<description><![CDATA[The term atomic is related to the atom, once considered the smallest possible unit of matter, unable to be broken into separate parts. When a routine is considered atomic, it cannot be interrupted during its execution. This can either be accomplished in hardware or simulated in software. In general, atomic instructions are provided in hardware [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=16&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p align="justify">The term atomic is related to the atom, once considered the smallest possible unit of matter, unable to be broken into separate parts. When a routine is considered atomic, it cannot be interrupted during its execution. This can either be accomplished in hardware or simulated in software. In general, atomic instructions are provided in hardware that is used to implement atomic routines in software. In our case, we define an atomic routine as one that can&#8217;t be found in an intermediate state. Atomicity is very important to avoiding race conditions.</p>
<p align="justify"><strong>Thread Interference</strong></p>
<blockquote><p> Consider a simple class called <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/example/Counter.java" class="SourceLink" target="_blank"><code><code>Counter</code></code></a></p>
<blockquote>
<pre>class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}</pre>
</blockquote>
</blockquote>
<p align="justify"><code>Counter</code> is designed so that each invocation of <code>increment</code> will add 1 to <code>c</code>, and each invocation of <code>decrement</code> will subtract 1 from <code>c</code>. However, if a <code>Counter</code> object is referenced from multiple threads, interference between threads may prevent this from happening as expected.</p>
<p align="justify">Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap.</p>
<p align="justify">It might not seem possible for operations on instances of <code>Counter</code> to interleave, since both operations on <code>c</code> are single, simple statements.  However, even simple statements can translate to multiple steps by the virtual machine. We won&#8217;t examine the specific steps the virtual machine takes — it is enough to know that the single expression <code>c++</code> can be decomposed into three steps:</p>
<blockquote>
<ol>
<li>Retrieve the current value of <code>c</code>.</li>
<li>Increment the retrieved value by 1.</li>
<li>Store the incremented value back in <code>c</code>.</li>
</ol>
</blockquote>
<p>The expression <code>c--</code> can be decomposed the same way, except that the second step decrements instead of increments.</p>
<p>Suppose Thread A invokes <code>increment</code> at about the same time Thread B invokes <code>decrement</code>. If the initial value of <code>c</code> is <code>0</code>, their interleaved actions might follow this sequence:</p>
<blockquote>
<ol>
<li>Thread A: Retrieve c.</li>
<li>Thread B: Retrieve c.</li>
<li>Thread A: Increment retrieved value; result is 1.</li>
<li>Thread B: Decrement retrieved value; result is -1.</li>
<li>Thread A: Store result in c; c is now 1.</li>
<li>Thread B: Store result in c; c is now -1.</li>
</ol>
</blockquote>
<p align="justify">Thread A&#8217;s result is lost, overwritten by Thread B. This particular interleaving is only one possibility. Under different circumstances it might be Thread B&#8217;s result that gets lost, or there could be no error at all. Because they are unpredictable, thread interference bugs can be difficult to detect and fix.</p>
<p><strong>Race Condition:<br />
</strong></p>
<p align="justify"> A race condition occurs when the order of execution of two or more threads may affect some variable or outcome in the program. It may turn out that all the different possible thread orderings have the same final effect on the application: the effect caused by the race condition may be insignificant, and may not even be relevant. For example, a character lost in the AsyncReadSocket may not affect the final outcome of the program. Alternately, the timing of the threading system may be such that the race condition never manifests itself, despite the fact that it exists in the code.</p>
<p align="justify">A race condition is a problem that is waiting to happen. Simple changes in the algorithm can cause race conditions to manifest themselves in problematic ways. And, since different virtual machines will have different orderings of thread execution, the developer should never let a race condition exist even if it is currently not causing a problem on the development system.</p>
<p><strong>Memory Consistency Errors</strong></p>
<p align="justify"><em>Memory consistency errors</em> occur when different threads have inconsistent views of what should be the same data. The causes of memory consistency errors are complex and beyond the scope of this tutorial. Fortunately, the programmer does not need a detailed understanding of these causes. All that is needed is a strategy for avoiding them.</p>
<p align="justify">The key to avoiding memory consistency errors is understanding the <em>happens-before</em> relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement. To see this, consider the following example. Suppose a simple <code>int</code> field is defined and initialized:</p>
<blockquote>
<pre>int counter = 0;</pre>
</blockquote>
<p align="justify">The <code>counter</code> field is shared between two threads, A and B. Suppose thread A increments <code>counter</code>:</p>
<blockquote>
<pre>counter++;</pre>
</blockquote>
<p>Then, shortly afterwords, thread B prints out <code>counter</code>:</p>
<blockquote>
<pre>System.out.println(counter);</pre>
</blockquote>
<p align="justify">If the two statements had been executed in the same thread, it would be safe to assume that the value printed out would be &#8220;1&#8243;. But if the two statements are executed in separate threads, the value printed out might well be &#8220;0&#8243;, because there&#8217;s no guarantee that thread A&#8217;s change to <code>counter</code> will be visible to thread B — unless the programmer has established a happens-before relationship between these two statements.</p>
<p align="justify">There are several actions that create happens-before relationships. One of them is synchronization, as we will see in the following sections.</p>
<p>We&#8217;ve already seen two actions that create happens-before relationships.</p>
<ul>
<li>
<p align="justify">When a statement invokes <code>Thread.start</code>, every    statement that has a happens-before relationship with that    statement also has a happens-before relationship with every    statement executed by the new thread. The effects of the code that    led up to the creation of the new thread are visible to the new    thread.</p>
</li>
<li>
<p align="justify"> When a thread terminates and causes a    <code>Thread.join</code> in another thread to return, then all the    statements executed by the terminated thread have a happens-before    relationship with all the statements following the successful join.    The effects of the code in the thread are now visible to the    thread that performed the join.</p>
</li>
</ul>
<p><strong>The Solution: Synchronisation</strong></p>
<p align="justify">The Java specification provides certain mechanisms that deal specifically with this problem.  The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized<em>    </em>statements.</p>
<p align="justify">The Java language provides the synchronized keyword; in comparison with other threading systems, this keyword allows the programmer access to a resource that is very similar to a mutex lock. For our purposes, it simply prevents two or more threads from calling our deduct() method at the same time:</p>
<blockquote><p>public class Account {<br />
private float total;</p>
<p>public synchronized boolean deduct(float t) {<br />
if (t &lt;= total) {<br />
total -= t;<br />
return true;<br />
}<br />
return false;<br />
}<br />
}</p></blockquote>
<p align="justify">By declaring the method as synchronized, if two users decide to access the method at the same time, the first user executes the deduct() method while the second user waits until the first user completes the deduct() method. Since only one user may execute the deduct() method at a time, the  race condition is eliminated. The effects can be effectively said to have the following impact:</p>
<ul>
<li>
<p align="justify">First, it is not possible for two invocations of synchronized    methods on the same object to interleave. When one thread is    executing a synchronized method for an object, all other threads    that invoke synchronized methods for the same object block    (suspend execution) until the first thread is done with the    object.</p>
</li>
<li>
<p align="justify">Second, when a synchronized method exits, it automatically    establishes a happens-before relationship with <em>any subsequent        invocation</em> of a synchronized method for the same object.    This guarantees that changes to the state of the object are    visible to all threads.</p>
</li>
</ul>
<p align="justify"><font color="#ff0000"><strong> Note: that constructors cannot be synchronized — using the <code>synchronized</code> keyword with a constructor is a syntax error. Synchronizing constructors doesn&#8217;t make sense, because only the thread that creates an object should have access to it while it is being constructed. </strong></font></p>
<p align="justify"><font color="#ff0000"><strong><strong>Warning:</strong>  When constructing an object that will be shared between threads, be very careful that a reference to the object does not &#8220;leak&#8221; prematurely. For example, suppose you want to maintain a <code>List</code> called <code>instances</code> containing every instance of class. You might be tempted to add the line </strong></font></p>
<blockquote>
<pre><font color="#ff0000"><strong>instances.add(this);
</strong></font></pre>
</blockquote>
<p align="justify"><font color="#ff0000"><strong> to your constructor. But then other threads can use <code>instances</code> to access the object before construction of the object is complete.</strong></font></p>
<p align="justify">With Java, there is a lock created in every object in the system. When a method is declared synchronized, the executing thread must grab the lock assigned to the object before it can continue. Upon completion of the method, the mechanism automatically releases the lock. Under the covers, the concept of synchronization is simple: when a method is declared as synchronized, it must have a token, which we call a lock. Once the method has acquired this lock (we may also say the lock has been checked out or grabbed), it executes the method and releases (we may also say returns) the lock once the method is finished. No matter how the method returns—including via an exception—the lock is released. There is only one lock per object, so if two separate threads try to call synchronized methods of the same object, only one can execute the method immediately; the other thread has to wait until the first thread releases the lock before it can execute the method.</p>
<p align="justify">Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object&#8217;s variables are done through <code>synchronized</code> methods. (An important exception: <code>final</code> fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/liveness.html">liveness</a>, as we&#8217;ll see later in this lesson.</p>
<p class="first" align="justify">The JVM organizes the data of a running Java application into several runtime data areas: one or more Java stacks, a heap, and a method area.</p>
<p align="justify">Inside the Java virtual machine, each thread is awarded a <em>Java stack</em>, which contains data no other thread can access, including the local variables, parameters, and return values of each method the thread has invoked. The data on the stack is limited to primitive types and object references. In the JVM, it is not possible to place the image of an actual object on the stack. All objects reside on the heap.</p>
<p align="justify">There is only one <em>heap</em> inside the JVM, and all threads share it. The heap contains nothing but objects. There is no way to place a solitary primitive type or object reference on the heap &#8212; these things must be part of an object. Arrays reside on the heap, including arrays of primitive types, but in Java, arrays are objects too.</p>
<p align="justify">Besides the Java stack and the heap, the other place data may reside in the JVM is the <em>method area</em>, which contains all the class (or static) variables used by the program. The method area is similar to the stack in that it contains only primitive types and object references. Unlike the stack, however, the class variables in the method area are shared by all threads.</p>
<p align="justify"><strong>Intrinsic Locks and Synchronization</strong></p>
<p align="justify">Synchronization is built around an internal entity known as the <em>intrinsic lock</em> or <em>monitor lock</em>. (The API specification often refers to this entity simply as a &#8220;monitor.&#8221;) Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object&#8217;s state and establishing happens-before relationships that are essential to visibility.</p>
<h3 align="justify">Object and class locks</h3>
<p align="justify">As described above, two memory areas in the Java virtual machine contain data shared by all threads. These are:</p>
<p align="justify">&nbsp;</p>
<ul>
<li>The heap, which contains all objects</li>
<li>The method area, which contains all class variables</li>
</ul>
<p align="justify">If multiple threads need to use the same objects or class variables concurrently, their access to the data must be properly managed. Otherwise, the program will have unpredictable behavior.</p>
<p align="justify">Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class <code>java.lang.Class</code>. When you lock a class, you are actually locking that class&#8217;s <code>Class</code> object. More on that later.</p>
<p align="justify">Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object&#8217;s fields has to <em>acquire</em> the object&#8217;s intrinsic lock before accessing them, and then <em>release</em> the intrinsic lock when it&#8217;s done with them. A thread is said to <em>own</em> the intrinsic lock between the time it has acquired the lock and released the lock. Note that threads need not obtain a lock to access instance or class variables. However, as long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.</p>
<p align="justify">When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquistion of the same lock.</p>
<p><strong>JVM  and Lock Management:</strong></p>
<p align="center"><img src="///C:/DOCUME%7E1/tshah/LOCALS%7E1/Temp/moz-screenshot.jpg" /></p>
<p align="justify"> To coordinate shared data access among multiple threads, the Java virtual machine associates a <em>lock</em> with each object and class. A lock is like a privilege that only one thread can &#8220;possess&#8221; at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock &#8212; maybe very soon, maybe later, possibly never &#8212; the JVM gives the lock to the thread. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.<br />
<strong><br />
Definition: Mutex Lock</strong></p>
<p align="justify">A mutex lock is also known as a mutually exclusive lock. This type of lock is provided by many threading systems as a means of synchronization. Basically, it is only possible for one thread to grab a mutex at a time: if two threads try to grab a mutex, only one succeeds. The other thread has to wait until the first thread releases the lock; it can then grab the lock and continue operation.</p>
<h3 align="justify">Monitors</h3>
<p align="justify">The JVM uses locks in conjunction with <em>monitors</em>. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.</p>
<p align="justify">Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code.</p>
<p align="justify">When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.</p>
<h3 align="justify">Multiple locks or Reentrant Synchronization</h3>
<p align="justify">Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.</p>
<p align="justify">Which implies, that a single thread is allowed to lock the same object multiple times. For each object, the JVM maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is incremented to one. Each time the thread acquires a lock on the same object, a count is incremented. Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.<br />
<strong><br />
Actual Implementation:</strong></p>
<p align="justify">Two opcodes, <code>monitorenter</code> and <code>monitorexit</code>, are used for synchronization blocks within methods, as shown in the table below.</p>
<p>MONITORS</p>
<table style="clear:both;">
<tr bgcolor="#ffffcc">
<th><strong>Opcode</strong></th>
<th><strong>Operand(s)</strong></th>
<th><strong>Description</strong></th>
</tr>
</table>
<p align="justify">When <code>monitorenter</code> is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If  the thread already owns the lock for that object, a count is incremented. Each time <code>monitorexit</code> is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.<a href="http://www.javaworld.com/javaworld/jw-07-1997/jw-07-hood.html?page=3"></a><br />
<strong><br />
Scope of a lock:</strong></p>
<p align="justify">The scope of a lock is defined as the period of time between when the lock is grabbed and released. In our examples so far, we have used only synchronized methods; this means that the scope of these locks is the period of time it takes to execute these methods. This is referred to as method scope.</p>
<p align="justify"><strong>Synchronized Statements </strong></p>
<p align="justify">To create a synchronized statement, you use the <code>synchronized</code> keyword with an expression that evaluates to an object reference. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:</p>
<blockquote>
<pre>public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}</pre>
</blockquote>
<p align="justify">In the case above, the statements contained within the synchronized block will not be executed until a lock is acquired on the current object (<code>this</code>). If instead of a <code>this</code> reference, the expression yielded a reference to another object, the lock associated with that object would be acquired before the thread continued.</p>
<p align="justify">In this example, the <code>addName</code> method needs to synchronize changes to <code>lastName</code> and <code>nameCount</code>, but also needs to avoid synchronizing invocations of other objects&#8217; methods. (Invoking other objects&#8217; methods from synchronized code can create liveness problems) .Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking <code>nameList.add</code>.</p>
<p align="justify">Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class <code>MsLunch</code> has two instance fields, <code>c1</code> and <code>c2</code>, that are never used together. All updates of these fields must be synchronized, but there&#8217;s no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with <code>this</code>, we create two objects solely to provide locks.</p>
<blockquote>
<pre>public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}</pre>
</blockquote>
<p align="justify">Use this idiom with extreme care.You must be absolutely sure that it really is safe to interleave access of the affected fields.</p>
<p align="justify"><strong>Note:</strong> How does a synchronized method behave in conjunction with a nonsynchronized method?<br />
Simply put, a synchronized method tries to grab the object lock, and a nonsynchronized method doesn&#8217;t. This means it is possible for many nonsynchronized methods to run in parallel with a synchronized method. Only one synchronized method runs at a time.</p>
<p align="justify">Note that a catch clause ensures the locked object will be unlocked even if an exception is thrown from within the synchronized block. No matter how the synchronized block is exited, the object lock acquired when the thread entered the block definitely will be released.</p>
<p><strong>Synchronized methods</strong></p>
<p align="justify"> To synchronize an entire method, you just include the <code>synchronized</code> keyword as one of the method qualifiers, as in:</p>
<pre>class HeatSync {

    private int[] intArray = new int[10];

    synchronized void reverseOrder() {
        int halfWay = intArray.length / 2;
        for (int i = 0; i &lt; halfWay; ++i) {
            int upperIndex = intArray.length - 1 - i;
            int save = intArray[upperIndex];
            intArray[upperIndex] = intArray[i];
            intArray[i] = save;
        }
    }
}</pre>
<p align="justify">The JVM does not use any special opcodes to invoke or return from synchronized methods. When the JVM resolves the symbolic reference to a method, it determines whether the method is synchronized. If it is, the JVM acquires a lock before invoking the method. For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized method completes, whether it completes by returning or by throwing an exception, the lock is released.<br />
You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the <code>Class</code> object associated with the class. Thus access to class&#8217;s static fields is controlled by a lock that&#8217;s distinct from the lock for any instance of the class.</p>
<p align="justify"><strong>Synchronized Method Versus Synchronized Block</strong>: <strong>Which to use?</strong></p>
<p align="justify">It is actually possible to use only the synchronized block mechanism, even when we need to synchronize the whole method. Picking the whole method is the simplest technique, but , it is possible to have deadlock because the scope is too large. It may also be inefficient to hold a lock for the section of code where it is actually not needed.</p>
<p align="justify">Using the synchronized block mechanism may also be a problem if too many locks are involved. As we shall see, it is possible to have a deadlock condition if we require too many locks to be grabbed. There is also an overhead in grabbing and releasing the lock, so it may be inefficient to free a lock just to grab it again a few lines of code later.</p>
<p align="justify"><strong>Synchronizing Static Methods</strong></p>
<p align="justify">So far, we kept referring to &#8220;obtaining the object lock.&#8221; But what about static methods? When a synchronized static method is called, which object are we referring to? A static method does not have a concept of the this reference. It is not possible to obtain the object lock of an object that does not exist. So how does synchronization of static methods work?</p>
<p align="justify">To answer this question, we will introduce the concept of a class lock. Just as there is an object lock that can be obtained for each instance of a class (object), there is a lock that can be obtained for each class. We will refer to this as the class lock . In terms of implementation, there is no such thing as a class lock, but it is a useful concept to help us understand how this all works.</p>
<p align="justify">When a static synchronized method is called, the program obtains the class lock before calling the method. This mechanism is identical to the case in which the method is not static; it is just a different lock. The same rule applies: if a synchronized static method calls another synchronized static method of the same class, the system is smart enough to support the nesting of class locks.</p>
<p align="justify">But how is the class lock related to the object lock? Apart from the functional relationship between the two locks, they are not operationally related at all. These are two distinct locks. The class lock can be grabbed and released independently of the object lock. If a nonstatic synchronized method calls a static synchronized method, it acquires both locks. Achieving deadlock between these two locks is a little difficult (but not impossible) to accomplish since a static method cannot call a nonstatic method without an object reference.</p>
<p align="justify">If a synchronized static method has access to an object reference, can it call synchronized methods of that object or use the object to lock a synchronized block? Yes: in this case the program first acquires the class lock when it calls the synchronized static method and then acquires the object lock of the particular object:</p>
<p>public class MyStatic {<br />
public synchronized static void staticMethod(MyStatic obj) {<br />
// Class lock acquired<br />
obj.nonStaticMethod();<br />
synchronized (obj) {<br />
// Class and object locks acquired<br />
}<br />
}<br />
public synchronized void nonStaticMethod() {<br />
// Object lock acquired<br />
}<br />
}</p>
<p align="justify">Can a nonstatic method grab the static lock without calling a synchronized static method? In other words, can a synchronized block apply to the class lock? For example, something like this:</p>
<p>public class ClassExample {<br />
synchronized void process() {<br />
synchronized (the class lock) {<br />
// Code to access static variables of the class<br />
}<br />
}<br />
}</p>
<p align="justify">The main reason for a nonstatic method to grab a class lock is to prevent a race condition for variables that apply to the class (i.e., static variables). This can be accomplished by calling a static synchronized method of the class. If for some reason this is not desired, we can also use the synchronized block mechanism on a common static object (using a static instance variable would probably be the best technique for storing such a common object). For example, we could use an object stored in a common location that can be accessed by all objects of a particular class type:</p>
<p>public class ClassExample {<br />
private static Object lockObject = new Object();<br />
synchronized void process() {<br />
synchronized (lockObject) {<br />
// Code to access static variables of the class<br />
}<br />
}<br />
}</p>
<p align="justify"><strong>The Class Lock and the Class Object</strong></p>
<p align="justify">In this example, we are using the object lock of the Class object as a common lock for the class. We are using this object because there is a one-to-one correspondence of class objects and classes in the system. We have also mentioned that when a synchronized static method is called, the system will grab the class lock.</p>
<p align="justify">It turns out that there is actually no such thing as a class lock. When a synchronized static method is called, the system grabs the object lock of the class object that represents the class. This means the class lock is the object lock of the corresponding class object. Using both static synchronized methods and synchronized blocks that use the class object lock can cause confusion.</p>
<p align="justify">Finally, if creating a new object is not desired, you may also obtain the class object (that is, the instance of the java.lang.Class class) that represents the class itself. Objects of this class are used to represent classes in the system. For our purposes, we are using this class because there is a one-to-one ratio of classes and objects of the Class class that represents the classes. This class object can be obtained as follows:</p>
<p>public class ClassExample {<br />
synchronized void process() {<br />
synchronized (Class.forName(&#8220;ClassExample&#8221;)) {<br />
// Code to access static variables of the class<br />
}<br />
}<br />
}</p>
<p>A call to the forName() method of the Class class returns this object. We can then use this class object as the locking object via the synchronized block mechanism.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=16&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/08/03/next-most-important-thread-lesson-synchronisation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>

		<media:content url="/DOCUME%7E1/tshah/LOCALS%7E1/Temp/moz-screenshot.jpg" medium="image" />
	</item>
		<item>
		<title>Threads &#8211; Interrupts</title>
		<link>http://tsjblog.wordpress.com/2007/08/01/threads-in/</link>
		<comments>http://tsjblog.wordpress.com/2007/08/01/threads-in/#comments</comments>
		<pubDate>Wed, 01 Aug 2007 20:57:46 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Java Multi-threading]]></category>
		<category><![CDATA[Java Threads]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/08/01/threads-in/</guid>
		<description><![CDATA[Interrupts
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It&#8217;s up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.A thread sends [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=14&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>Interrupts</strong></p>
<p align="justify">An interrupt is an indication to a thread that it should stop what it is doing and do something else. It&#8217;s up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.</p>
<p><strong>Supporting Interruption</strong></p>
<p>How does a thread support its own interruption? This depends on what it&#8217;s currently doing. If the thread is frequently invoking methods that throw InterruptedException, it simply returns from the run method after it catches that exception. For example, suppose the central message loop in the SleepMessages example were in the run method of a thread&#8217;s Runnable object. Then it might be modified as follows to support interrupts:</p>
<p>for (int i = 0; i &lt; importantInfo.length; i++) {<br />
//Pause for 4 seconds<br />
try {<br />
Thread.sleep(4000);<br />
} catch (InterruptedException e) {<br />
//We&#8217;ve been interrupted: no more messages.<br />
return;<br />
}<br />
//Print a message<br />
System.out.println(importantInfo[i]);<br />
}</p>
<p>Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.</p>
<p align="justify">What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:</p>
<p>         for (int i = 0; i &lt; inputs.length; i++) {<br />
heavyCrunch(inputs[i]);<br />
if (Thread.interrupted()) {<br />
//We&#8217;ve been interrupted: no more crunching.<br />
return;<br />
}<br />
}</p>
<p>In this simple example, the code simply tests for the interrupt and exits the thread if one has been received. In more complex applications, it might make more sense to throw an InterruptedException:</p>
<p>if (Thread.interrupted()) {<br />
throw new InterruptedException();<br />
}</p>
<p>This allows interrupt handling code to be centralized in a catch clause.</p>
<p><strong>The Interrupt Status Flag</strong></p>
<p align="justify">The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.</p>
<p align="justify">    By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it&#8217;s always possible that interrupt status will immediately be set again, by another thread invoking interrupt.</p>
<p><strong>Joins</strong></p>
<div align="justify">The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
</div>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t.join();</p>
<div align="justify">causes the current thread to pause execution until t&#8217;s thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
</div>
<p>&nbsp;Like sleep, join responds to an interrupt by exiting with an InterruptedException. </p>
<p>Finally, an example:</p>
<p>The SimpleThreads Example</p>
<div align="justify">&nbsp;&nbsp;&nbsp; The following example brings together some of the concepts of this section. SimpleThreads consists of two threads. The first is the main thread that every Java application has. The main thread creates a new thread from the Runnable object, MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it.
</div>
<div align="justify">&nbsp;&nbsp;&nbsp; The MessageLoop thread prints out a series of messages. If interrupted before it has printed all its messages, the MessageLoop thread prints a message and exits.
</div>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public class SimpleThreads {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Display a message, preceded by the name of the current thread<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; static void threadMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String threadName = Thread.currentThread().getName();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.format(&#8220;%s: %s%n&#8221;, threadName, message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private static class MessageLoop implements Runnable {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void run() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String importantInfo[] = {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8220;Mares eat oats&#8221;,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8220;Does eat oats&#8221;,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8220;Little lambs eat ivy&#8221;,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8220;A kid will eat ivy too&#8221;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; importantInfo.length; i++) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Pause for 4 seconds<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Thread.sleep(4000);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Print a message<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(importantInfo[i]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (InterruptedException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(&#8220;I wasn&#8217;t done!&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static void main(String args[]) throws InterruptedException {</p>
<p>&nbsp;&nbsp;&nbsp;<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Delay, in milliseconds before we interrupt MessageLoop<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //thread (default one hour).<br />
&nbsp;</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; long patience = 1000 * 60 * 60;</p>
<p>&nbsp;&nbsp;&nbsp;<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //If command line argument present, gives patience in seconds.<br />
&nbsp;</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (args.length &gt; 0) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; patience = Long.parseLong(args[0]) * 1000;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (NumberFormatException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.err.println(&#8220;Argument must be an integer.&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.exit(1);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(&#8220;Starting MessageLoop thread&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; long startTime = System.currentTimeMillis();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Thread t = new Thread(new MessageLoop());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t.start();</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(&#8220;Waiting for MessageLoop thread to finish&#8221;);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>//loop until MessageLoop thread exits</strong><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while (t.isAlive()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(&#8220;Still waiting&#8230;&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b> //Wait maximum of 1 second for MessageLoop thread to<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //finish.</b><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t.join(1000);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (((System.currentTimeMillis() &#8211; startTime) &gt; patience) &amp;&amp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t.isAlive()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(&#8220;Tired of waiting!&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t.interrupt();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Shouldn&#8217;t be long now &#8212; wait indefinitely<br />
</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; t.join();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; threadMessage(&#8220;Finally!&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=14&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/08/01/threads-in/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Thread Basics</title>
		<link>http://tsjblog.wordpress.com/2007/08/01/thread-basics/</link>
		<comments>http://tsjblog.wordpress.com/2007/08/01/thread-basics/#comments</comments>
		<pubDate>Wed, 01 Aug 2007 07:52:44 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Threads]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/08/01/thread-basics/</guid>
		<description><![CDATA[ An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:

Provide a Runnable object. The  Runnable    interface defines a single method, run, meant to    contain the code executed in the thread. The Runnable [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=13&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p align="justify"> An application that creates an instance of <code>Thread</code> must provide the code that will run in that thread. There are two ways to do this:</p>
<ul>
<li><strong>Provide a Runnable<code> </code>object.</strong> The  <a href="http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html" class="APILink" target="_blank"><code>Runnable</code></a>    interface defines a single method, <code>run</code>, meant to    contain the code executed in the thread. The <code>Runnable</code>    object is passed to the <code>Thread</code> constructor, as in the  <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/example/HelloRunnable.java" class="SourceLink" target="_blank"><code><code>HelloRunnable</code></code></a> example:</li>
</ul>
<p>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; public class HelloRunnable implements Runnable<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; public void run() {&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.println(&#8220;Hello from a thread!&#8221;);<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; public static void main(String args[]) {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; (new Thread(new HelloRunnable())).start();<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }</p>
<ul>
<li>
<p align="justify"><strong>Subclass Thread.</strong> The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the  <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/example/HelloThread.java" class="SourceLink" target="_blank"><code><code>HelloThread</code></code></a> example.</p>
<p>public class HelloThread extends Thread</li>
</ul>
<p>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void run() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println(&#8220;Hello from a thread!&#8221;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; public static void main(String args[]) {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; (new HelloThread()).start();<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p align="justify">Notice that both examples invoke Thread.start in order to start the new thread.The first idiom, which employs a Runnable object, is more general, because the Runnable  <code></code> object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. We focus on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs.The Thread class defines a number of methods useful for thread management. These include static methods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and Thread object.</p>
<p>Something to remember:  </p>
<div align="justify">In Java, every thread begins by executing a <strong>run()</strong> method in a particular object.  <strong>Run()</strong> is declared to be <strong>public</strong>, takes no arguments, has no return value, and is not allowed to throw any exceptions.  Any class can implement a <strong>run()</strong> method by declaring that the class implements the <strong>Runnable</strong> interface.</div>
<p align="justify">&nbsp;</p>
<p align="justify">
<p><strong> Thread.sleep</strong></p>
<h3> sleep</h3>
<p>public static void <strong>sleep</strong>(long millis) throws <a href="http://java.sun.com/j2se/1.3/docs/api/java/lang/InterruptedException.html">InterruptedException</a></p>
<dl>
<dd>Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.</dd>
<dt>
</dt>
<dd>
</dd>
<dd>
<dl>
<dt>
</dt>
<dt><strong>Parameters:</strong></dt>
<dd>millis &#8211; the length of time to sleep in milliseconds.</dd>
<dt>
</dt>
<dt><strong>Throws:</strong></dt>
<dd>
<p align="justify"><a href="http://java.sun.com/j2se/1.3/docs/api/java/lang/InterruptedException.html">InterruptedException</a>- if another thread has interrupted             the current thread.  The <em>interrupted status</em> of the             current thread is cleared when this exception is thrown.</p>
</dd>
</dl>
</dd>
</dl>
<p align="justify">This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep <code></code> method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.</p>
<p align="justify"> Two overloaded versions of sleep<code></code> are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we&#8217;ll see in a later section. In any case, you cannot assume that invoking sleep<code></code> will suspend the thread for precisely the time period specified.</p>
<p align="justify"> The  <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/example/SleepMessages.java" class="SourceLink" target="_blank">SleepMessages</a> example uses sleep to print messages at four-second intervals:</p>
<p>                        public class SleepMessages {</p>
<p>public static void main(String args[]) throws InterruptedException<br />
{</p>
<p>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; String importantInfo[] = {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &#8220;Mares eat oats&#8221;,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &#8220;Does eat oats&#8221;,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &#8220;Little lambs eat ivy&#8221;,<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &#8220;A kid will eat ivy too&#8221;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; };<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; importantInfo.length; i++)<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Pause for 4 seconds<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Thread.sleep(4000);<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Print a message<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.println(importantInfo[i]);<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; }<br />
}</p>
<p align="justify">Notice that main declares that it throws    InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active.  Since this application has not defined another thread to cause the interrupt, it doesn&#8217;t bother to catch InterruptedException.</p>
<p align="justify">&nbsp;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=13&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/08/01/thread-basics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Collections trivia &#8211; Unmodifiable Collections</title>
		<link>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-unmodifiable-collections/</link>
		<comments>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-unmodifiable-collections/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 23:17:25 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/07/10/collections-trivia-unmodifiable-collections/</guid>
		<description><![CDATA[  Unmodifiable Collections can be easily created using various static methods  which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException. 
Collection&#60;T&#62; unmodifiableCollection(Collection&#60;? extends T&#62; c)
List&#60;T&#62; unmodifiableList(List&#60;? extends T&#62; list)
Set&#60;T&#62; unmodifiableSet(Set&#60;? extends T&#62; s)
SortedSet&#60;T&#62; unmodifiableSortedSet(SortedSet&#60;T&#62; s)
import java.util.*;
public class Unmod{
public static void [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=6&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;"><font face="Verdana,Arial,Helvetica" size="2"> </font><font face="Verdana,Arial,Helvetica" size="2"> Unmodifiable Collections can be easily created using various static methods  which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException. </font></p>
<p>Collection&lt;T&gt; unmodifiableCollection(Collection&lt;? extends T&gt; c)</p>
<p>List&lt;T&gt; unmodifiableList(List&lt;? extends T&gt; list)</p>
<p>Set&lt;T&gt; unmodifiableSet(Set&lt;? extends T&gt; s)</p>
<p>SortedSet&lt;T&gt; unmodifiableSortedSet(SortedSet&lt;T&gt; s)<br />
import java.util.*;<br />
public class Unmod{</p>
<p>public static void main(String[] args){</p>
<p>List&lt;String&gt; strlist = new ArrayList&lt;String&gt;();</p>
<p>strlist.add(&#8220;C&#8221;);</p>
<p>strlist.add(&#8220;B&#8221;);</p>
<p>strlist.add(&#8220;A&#8221;);</p>
<p>Collection&lt;String&gt; unmodstrlist = Unmod.makeUnmodifiable(strlist);</p>
<p>// unmodstrlist.add(&#8220;G&#8221;); throws UnsupportedOperationException<br />
Set&lt;String&gt; strset = new TreeSet&lt;String&gt;();</p>
<p>strset.add(&#8220;C&#8221;);</p>
<p>strset.add(&#8220;B&#8221;);</p>
<p>strset.add(&#8220;A&#8221;);</p>
<p>Collection&lt;String&gt; unmodstrset = Unmod.makeUnmodifiable(strset);</p>
<p>// unmodstrset.add(&#8220;G&#8221;); throws UnsupportedOperationException</p>
<p>}<br />
public static Collection&lt;String&gt; makeUnmodifiable(Collection&lt;String&gt; c){</p>
<p>return(Collections.unmodifiableCollection(c));</p>
<p>}</p>
<p>}</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/6/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/6/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=6&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-unmodifiable-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Collections trivia</title>
		<link>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-2/</link>
		<comments>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-2/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 23:09:21 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Collections]]></category>
		<category><![CDATA[Java Collections]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/07/10/collections-trivia-2/</guid>
		<description><![CDATA[How would you preserve the order of insertion of entries into a Map?public class LinkedHashMap
extends HashMap
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=5&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">How would you preserve the order of insertion of entries into a Map?public class LinkedHashMap<br />
extends HashMap</p>
<p>Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)</p>
<p>This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap. It can be used to produce a copy of a map that has the same order as the original, regardless of the original map&#8217;s implementation:</p>
<p>void foo(Map m) {<br />
Map copy = new LinkedHashMap(m);<br />
&#8230;<br />
}<br />
This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)</p>
<p>A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes). The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map&#8217;s entry set iterator. No other methods generate entry accesses. In particular, operations on collection-views do not affect the order of iteration of the backing map.</p>
<p>The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.</p>
<p>This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.</p>
<p><em><strong><font color="#ff6666">A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.<br />
</font></strong></em></p>
<p>Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be &#8220;wrapped&#8221; using the Collections.synchronizedMapmethod. This is best done at creation time, to prevent accidental unsynchronized access:</p>
<p>Map m = Collections.synchronizedMap(new LinkedHashMap(&#8230;));<br />
A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.)</p>
<p>The iterators returned by the iterator methods of the collections returned by all of this class&#8217;s collection view methods are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator&#8217;s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.</p>
<p>Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.</p>
<p>This class is a member of the Java Collections Framework.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/5/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/5/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=5&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Collections trivia &#8211; static methods on Collections</title>
		<link>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-static-methods-on-collections/</link>
		<comments>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-static-methods-on-collections/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 19:55:56 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Java Basics.]]></category>
		<category><![CDATA[Java Collections]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/07/11/collections-trivia-static-methods-on-collections/</guid>
		<description><![CDATA[
Most of us know only of the Collections interface. But there is also a collections class which has a bunch of really useful static methods that can be applied to any collection from the java Collections Framework. Take a look here. 




public class Collections
extends Object

&#160;
 This class consists exclusively of static methods that operate on [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=7&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><dl>
<dt>Most of us know only of the Collections interface. But there is also a collections class which has a bunch of really useful static methods that can be applied to any collection from the java Collections Framework. Take a look <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html">here.</a> </dt>
<dt>
</dt>
<dt>
</dt>
<dt>public class <strong>Collections</strong></dt>
<dt>extends <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html" title="class in java.lang">Object</a></dt>
</dl>
<p style="text-align:justify;">&nbsp;</p>
<p style="text-align:justify;"> This class consists exclusively of static methods that operate on or return collections.  It contains polymorphic algorithms that operate on collections, &#8220;wrappers&#8221;, which return a new collection backed by a specified collection, and a few other odds and ends.</p>
<p style="text-align:justify;">The methods of this class all throw a <tt>NullPointerException</tt> if the collections provided to them are null.</p>
<p style="text-align:justify;">The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the <em>implementation</em>.  Such descriptions should be regarded as <em>implementation notes</em>, rather than parts of the <em>specification</em>.  Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to.  (For example, the algorithm used by <tt>sort</tt> does not have to be a mergesort, but it does have to be <em>stable</em>.)</p>
<p style="text-align:justify;">The &#8220;destructive&#8221; algorithms contained in this class, that is, the algorithms that modify the collection on which they operate, are specified to throw <tt>UnsupportedOperationException</tt> if the collection does not support the appropriate mutation primitive(s), such as the <tt>set</tt> method.  These algorithms may, but are not required to, throw this exception if an invocation would have no effect on the collection.  For example, invoking the <tt>sort</tt> method on an unmodifiable list that is already sorted may or may not throw <tt>UnsupportedOperationException</tt>.</p>
<p style="text-align:justify;">This class is a member of the  <a href="http://java.sun.com/j2se/1.4.2/docs/guide/collections/index.html"> Java Collections Framework</a>.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=7&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/07/10/collections-trivia-static-methods-on-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>
	</item>
		<item>
		<title>Identity Hash Maps</title>
		<link>http://tsjblog.wordpress.com/2007/07/10/identity-hash-maps/</link>
		<comments>http://tsjblog.wordpress.com/2007/07/10/identity-hash-maps/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 18:46:58 +0000</pubDate>
		<dc:creator>tanvis</dc:creator>
				<category><![CDATA[Java Basics.]]></category>
		<category><![CDATA[Java Collections]]></category>

		<guid isPermaLink="false">http://tsjblog.wordpress.com/2007/07/10/identity-hash-maps/</guid>
		<description><![CDATA[

public class IdentityHashMap
extends AbstractMap
implements Map, Serializable, Cloneable

 This class implements the Map interface with a hash table, using reference-equality(has to be the same instance of the object) in place of object-equality(two individual objects which are equal in every respect) when comparing keys (and values).  In other words, in an IdentityHashMap, two keys k1 and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=3&subd=tsjblog&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p align="justify">
<dl>
<dt>public class <strong>IdentityHashMap</strong></dt>
<dt>extends <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/AbstractMap.html" title="class in java.util">AbstractMap</a></dt>
<dt>implements <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html" title="interface in java.util">Map</a>, <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html" title="interface in java.io">Serializable</a>, <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html" title="interface in java.lang">Cloneable</a></dt>
</dl>
<p align="justify"> This class implements the <tt>Map</tt> interface with a hash table, using <em><strong><font color="#ff6666">reference-equality(</font></strong><strong><font color="#ff6666">has to be the same instance of the object)</font></strong></em> in place of <strong><em><font color="#ff6666">object-equality(two individual objects which are equal in every respect)</font></em></strong> when comparing keys (and values).  In other words, in an <tt>IdentityHashMap</tt>, two keys <tt>k1</tt> and <tt>k2</tt> are considered equal if and only if <tt>(k1==k2)</tt>.  (In normal <tt>Map</tt> implementations (like <tt>HashMap</tt>) two keys <tt>k1</tt> and <tt>k2</tt> are considered equal if and only if <tt>(k1==null ? k2==null : k1.equals(k2))</tt>)</p>
<p align="justify"><strong>This class is <em>not</em> a general-purpose <tt>Map</tt> implementation!  While this class implements the <tt>Map</tt> interface, it intentionally violates <tt>Map's</tt> general contract, which mandates the use of the <tt>equals</tt> method when comparing objects.  This class is designed for use only in the rare cases wherein reference-equality semantics are required (generally when checking for single-copies &#8211; Consider an algorithm to find a loop in a linked list).<br />
</strong></p>
<p align="justify">A typical use of this class is <strong><em>topology-preserving object graph transformations</em>,</strong> such as serialization or deep-copying.  To perform such a transformation, a program must maintain a &#8220;node table&#8221; that keeps track of all the object references that have already been processed.  The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain <em>proxy objects</em>.  For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.</p>
<p align="justify">This class provides all of the optional map operations, and permits <tt>null</tt> values and the <tt>null</tt> key.  This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.</p>
<p><strong><font color="#ff0000">This class provides constant-time performance for the basic operations (<tt>get</tt> and <tt>put</tt>), assuming the system identity hash function (<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#identityHashCode%28java.lang.Object%29"><code>System.identityHashCode(Object)</code></a>) disperses elements properly among the buckets.</font></strong></p>
<p align="justify">&nbsp;</p>
<p align="justify">This class has one tuning parameter (which affects performance but not semantics): <em>expected maximum size</em>.  This parameter is the maximum number of key-value mappings that the map is expected to hold.  <font color="#cc0000"><strong>Internally, this parameter is used to determine the number of buckets initially comprising the hash table.  The precise relationship between the expected maximum size and the number of buckets is unspecified.</strong></font></p>
<p align="justify">If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased Increasing the number of buckets (&#8220;rehashing&#8221;) may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size.  On the other hand, iteration over collection views requires time proportional to the the number of buckets in the hash table, so it pays not to set the expected maximum size too high if you are especially concerned with iteration performance or memory usage.</p>
<p align="justify"><strong>Note that this implementation is not synchronized.</strong> If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it <em>must</em> be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)  This is typically accomplished by synchronizing on some object that naturally encapsulates the map.  If no such object exists, the map should be &#8220;wrapped&#8221; using the <tt>Collections.synchronizedMap</tt> method.  This is best done at creation time, to prevent accidental unsynchronized access to the map:</p>
<pre>     Map m = Collections.synchronizedMap(new HashMap(...));</pre>
<p align="justify">The iterators returned by all of this class&#8217;s &#8220;collection view methods&#8221; are <em>fail-fast</em>: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator&#8217;s own <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a <tt>ConcurrentModificationException</tt>.  Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.</p>
<p align="justify">Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.  Fail-fast iterators throw <tt>ConcurrentModificationException</tt> on a best-effort basis.  Therefore, it would be wrong to write a program that depended on this exception for its correctness: <em>fail-fast iterators should be used only to detect bugs.</em></p>
<p align="justify"><strong><font color="#ff0000">Implementation note: This is a simple <em>linear-probe</em> hash table, as described for example in texts by Sedgewick and Knuth.  The array alternates holding keys and values.  (This has better locality for large tables than does using separate arrays.)  For many JRE implementations and operation mixes, this class will yield better performance than <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html" title="class in java.util"><code>HashMap</code></a> (which uses <em>chaining</em> rather than linear-probing).<br />
</font></strong></p>
<h3 align="justify"><span class="mw-headline">Chaining</span></h3>
<p align="justify">&nbsp;</p>
<p> <a href="http://en.wikipedia.org/wiki/Image:HASHTB32.svg" class="internal" title="Hash collision resolved by chaining."><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/HASHTB32.svg/362px-HASHTB32.svg.png" alt="Hash collision resolved by chaining." longdesc="/wiki/Image:HASHTB32.svg" class="thumbimage" height="195" width="362" /></a></p>
<p>Hash collision resolved by chaining.</p>
<p align="justify">&nbsp;</p>
<p align="justify">In the simplest chained hash table technique, each slot in the array references a <a href="http://en.wikipedia.org/wiki/Linked_list" title="Linked list">linked list</a> of inserted records that collide to the same slot. Insertion requires finding the correct slot, and appending to either end of the list in that slot; deletion requires searching the list and removal.</p>
<p align="justify">&nbsp;</p>
<p align="justify">Chained hash tables have advantages over open addressed hash tables in that the removal operation is simple and resizing the table can be postponed for a much longer time because performance <a href="http://en.wikipedia.org/wiki/Graceful_degradation" title="Graceful degradation">degrades more gracefully</a> even when every slot is used. Indeed, many chaining hash tables may not require resizing at all since performance degradation is linear as the table fills. For example, a chaining hash table containing twice its recommended capacity of data would only be about twice as slow on average as the same table at its recommended capacity.</p>
<p align="justify">&nbsp;</p>
<p align="justify">Chained hash tables inherit the disadvantages of linked lists. When storing small records, the overhead of the linked list can be significant. An additional disadvantage is that traversing a linked list has poor <a href="http://en.wikipedia.org/wiki/Locality_of_reference" title="Locality of reference">cache performance</a>.</p>
<p align="justify">&nbsp;</p>
<p align="justify">Alternative data structures can be used for chains instead of linked lists. By using a <a href="http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree" title="Self-balancing binary search tree">self-balancing tree</a>, for example, the theoretical worst-case time of a hash table can be brought down to O(log <em>n</em>) rather than O(<em>n</em>). However, since each list is intended to be short, this approach is usually inefficient unless the hash table is designed to run at full capacity or there are unusually high collision rates, as might occur in input designed to cause collisions. <a href="http://en.wikipedia.org/wiki/Dynamic_array" title="Dynamic array">Dynamic arrays</a> can also be used to decrease space overhead and improve cache performance when records are small.</p>
<p align="justify">&nbsp;</p>
<p align="justify">Some chaining implementations use an optimization where the first record of each chain is stored in the table. Although this can increase performance, it is generally not recommended: chaining tables with reasonable load factors contain a large proportion of empty slots, and the larger slot size causes them to waste large amounts of space.</p>
<p align="justify">&nbsp;</p>
<p align="justify"><a title="Open_addressing" name="Open_addressing" id="Open_addressing"></a></p>
<p align="justify">&nbsp;</p>
<h3 align="justify"><span class="editsection"></span> <span class="mw-headline">Open addressing</span></h3>
<p align="justify">&nbsp;</p>
<p> <a href="http://en.wikipedia.org/wiki/Image:HASHTB12.svg" class="internal" title="Hash collision resolved by linear probing (interval=1)."><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/90/HASHTB12.svg/362px-HASHTB12.svg.png" alt="Hash collision resolved by linear probing (interval=1)." longdesc="/wiki/Image:HASHTB12.svg" class="thumbimage" height="226" width="362" /></a></p>
<p>Hash collision resolved by linear probing (interval=1).</p>
<p align="justify">&nbsp;</p>
<p align="justify">Open addressing hash tables store the records directly within the array. This approach is also called <em>closed hashing</em>. A hash collision is resolved by <em>probing</em>, or searching through alternate locations in the array (the <em>probe sequence</em>) until either the target record is found, or an unused array slot is found, which indicates that there is no such key in the table. Well known probe sequences include:</p>
<p align="justify">
<dl>
<dt><a href="http://en.wikipedia.org/wiki/Linear_probing" title="Linear probing">linear probing</a> </dt>
<dd>in which the interval between probes is fixed&#8211;often at 1.</dd>
<dt><a href="http://en.wikipedia.org/wiki/Quadratic_probing" title="Quadratic probing">quadratic probing</a> </dt>
<dd>in which the interval between probes increases linearly (hence, the indices are described by a quadratic function).</dd>
<dt><a href="http://en.wikipedia.org/wiki/Double_hashing" title="Double hashing">double hashing</a> </dt>
<dd>in which the interval between probes is fixed for each record but is computed by another hash function.</dd>
</dl>
<p align="justify">The main tradeoffs between these methods are that linear probing has the best cache performance but is most sensitive to clustering, while double hashing has poor cache performance but exhibits virtually no clustering; quadratic probing falls in-between in both areas. Double hashing can also require more computation than other forms of probing. Some open addressing methods, such as <a href="http://en.wikipedia.org/w/index.php?title=Last-come-first-served_hashing&amp;action=edit" class="new" title="Last-come-first-served hashing">last-come-first-served hashing</a> and <a href="http://en.wikipedia.org/wiki/Cuckoo_hashing" title="Cuckoo hashing">cuckoo hashing</a> move existing keys around in the array to make room for the new key. This gives better maximum search times than the methods based on probing.</p>
<p align="justify">&nbsp;</p>
<p align="justify">A critical influence on performance of an open addressing hash table is the <em>load factor</em>; that is, the proportion of the slots in the array that are used. As the load factor increases towards 100%, the number of probes that may be required to find or insert a given key rises dramatically. Once the table becomes full, probing algorithms may even fail to terminate. Even with good hash functions, load factors are normally limited to 80%. A poor hash function can exhibit poor performance even at very low load factors by generating significant clustering. What causes hash functions to cluster is not well understood, and it is easy to unintentionally write a hash function which causes severe clustering.</p>
<p align="justify">&nbsp;</p>
<p align="justify">&nbsp;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/tsjblog.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/tsjblog.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tsjblog.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tsjblog.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tsjblog.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tsjblog.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tsjblog.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tsjblog.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tsjblog.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tsjblog.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tsjblog.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tsjblog.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=tsjblog.wordpress.com&blog=1346012&post=3&subd=tsjblog&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://tsjblog.wordpress.com/2007/07/10/identity-hash-maps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa7205506d775a9e999f87dd595bc57c?s=96&#38;d=identicon" medium="image">
			<media:title type="html">tanvis</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/HASHTB32.svg/362px-HASHTB32.svg.png" medium="image">
			<media:title type="html">Hash collision resolved by chaining.</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/commons/thumb/9/90/HASHTB12.svg/362px-HASHTB12.svg.png" medium="image">
			<media:title type="html">Hash collision resolved by linear probing (interval=1).</media:title>
		</media:content>
	</item>
	</channel>
</rss>