<?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:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>shiv Pratap singh</title>
	<atom:link href="http://shivpratap.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://shivpratap.wordpress.com</link>
	<description>what is ur Question?</description>
	<lastBuildDate>Sun, 02 Dec 2007 05:12:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='shivpratap.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>shiv Pratap singh</title>
		<link>http://shivpratap.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://shivpratap.wordpress.com/osd.xml" title="shiv Pratap singh" />
	<atom:link rel='hub' href='http://shivpratap.wordpress.com/?pushpress=hub'/>
		<item>
		<title>MULTITHREADING JAVA</title>
		<link>http://shivpratap.wordpress.com/2007/10/17/multithreading-java/</link>
		<comments>http://shivpratap.wordpress.com/2007/10/17/multithreading-java/#comments</comments>
		<pubDate>Wed, 17 Oct 2007 03:24:43 +0000</pubDate>
		<dc:creator>shiv pratap singh</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://shivpratap.wordpress.com/2007/10/17/multithreading-java/</guid>
		<description><![CDATA[Concurrency Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=shivpratap.wordpress.com&amp;blog=1141367&amp;post=11&amp;subd=shivpratap&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="Section1">
<h1><font size="5" color="#000099"><span>Concurrency</span></font></h1>
<p class="MyBody"><span>Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor should always be ready to respond to keyboard and mouse events; no matter how busy it is reformatting text or updating the display. Software that can do such things is known as concurrent software. </span></p>
<p class="MyBody"><span>The Java platform is designed from the ground up to support concurrent programming, with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs. This lesson introduces the platform&#8217;s basic concurrency support and summarizes some of the high-level APIs in the </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">java.util.concurrent</span></span></font><span> packages. </span></p>
<h2><font size="4" color="#006600"><span>Processes and Threads</span></font></h2>
<p class="MyBody"><span>In concurrent programming, there are two basic units of execution: <em>processes</em> and <em>threads</em><em>. </em>In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important. </span></p>
<p class="MyBody"><span>A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing. </span></p>
<p class="MyBody"><span>It&#8217;s becoming more and more common for computer systems to have multiple processors or processors with multiple execution cores. This greatly enhances a system&#8217;s capacity for concurrent execution of processes and threads — but concurrency is possible even on simple systems, without multiple processors or execution cores.</span></p>
<h3><span><font color="#666666">Processes</font><br />
</span></h3>
<p class="MyBody"><span>A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. </span></p>
<p class="MyBody"><span>Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes. To facilitate communication between processes, most operating systems support <strong>Inter Process Communication</strong> (IPC) resources, such as <strong>pipes</strong> and <strong>sockets</strong>. IPC is used not just for communication between processes on the same system, but processes on different systems. </span></p>
<p class="MyBody"><span>Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a <font color="#3333ff"><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html">ProcessBuilder</a></font> object.</span></p>
<h3><font color="#666666"><span>Threads</span></font></h3>
<p class="MyBody"><span>Threads are sometimes called <strong><em>lightweight processes</em></strong>. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. </span></p>
<p class="MyBody"><span>Threads exist within a process — every process has at least one thread. Threads share the process&#8217;s resources, including memory and open files. This makes for efficient, but potentially problematic, communication. </span></p>
<p class="MyBody"><span>Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread — or several, if you count <strong><em>system threads </em></strong><em>that do things like memory management and signal handling</em>. But from the application programmer&#8217;s point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads, as we&#8217;ll demonstrate in the next section. </span></p>
<h2><font color="#006600"><span>Thread Objects</span></font></h2>
<p class="MyBody"><span>Each thread is associated with an instance of the class <font color="#3333ff"><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html">Thread</a></font>. There are two basic strategies for using Thread objects to create a concurrent application.</span></p>
<ul>
<li><span>To directly control thread creation and management, simply instantiate Thread each time the application needs to initiate an asynchronous task. </span></li>
</ul>
<ul>
<li><span>To abstract thread management from the rest of your application, pass the application&#8217;s tasks to an <strong>executor</strong>. </span></li>
</ul>
<h3><font color="#666666"><span>Defining and Starting a Thread</span></font></h3>
<p class="MyBody"><span>An application that creates an instance of </span><span style="font-size:11pt;">Thread</span><span> must provide the code that will run in that thread. There are two ways to do this: </span></p>
<ul>
<li><span>Provide a </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Runnable</span></span></font> <span>object. The <font color="#3333ff"><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html">Runnable</a></font> interface defines a single method, </span><span style="font-size:11pt;">run</span><span>, meant to contain the code executed in the thread. The </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Runnable</span></span></font> <span>object is passed to the <font color="#993399"><span style="font-family:Courier New;">Thread </span></font>constructor, as in the following example:</span></li>
</ul>
<p><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> HelloRunnable <strong><span style="color:#7f0055;">implements</span></strong> Runnable {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        System.<em><span style="color:#0000c0;">out</span></em>.println(<span style="color:#2a00ff;">&#8220;Hello from a thread!&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String args[]) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        (<strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> HelloRunnable())).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<ul>
<li><span>Subclass <font color="#993399">Thread</font></span><span>. <em>The Thread class itself implements Runnable</em>, though it’s run method does nothing. An application can subclass </span><span><font color="#993399">Thread</font></span><span>, providing its own implementation of run, as in the following example:</span></li>
</ul>
<p><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> HelloThread <strong><span style="color:#7f0055;">extends</span></strong> Thread {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        System.<em><span style="color:#0000c0;">out</span></em>.println(<span style="color:#2a00ff;">&#8220;Hello from a thread!&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String args[]) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        (<strong><span style="color:#7f0055;">new</span></strong> HelloThread()).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span><em>Notice that both examples invoke </em></span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;"><em>Thread.start</em></span></span></font><span><em> in order to start the new thread.</em> </span></p>
<p class="MyBody"><span>Which of these idioms should you use? The first idiom, which employs a <font color="#993399"><span style="font-family:Courier New;">Runnable </span></font>object, is more general, because the </span><span><font color="#993399"><span style="font-family:Courier New;">Runnable </span></font></span><span>object can subclass a class other than </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread</span></span></font><span>. 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 </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread</span></span></font><span><span style="font-family:Courier New;">. </span>This lesson focuses on the first approach, which separates the </span><span><font color="#993399"><span style="font-family:Courier New;">Runnable </span></font></span><span>task from the </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread </span></span></font><span>object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later. </span></p>
<p class="MyBody"><span>The </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread </span></span></font><span>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 </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread </span></span></font><span>object. We&#8217;ll examine some of these methods in the following sections. </span></p>
<h3><font color="#666666"><span>Pausing Execution with Sleep</span></font></h3>
<p class="MyBody"><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread.sleep</span></span></font><span> causes the current thread to suspend execution for a specified period. 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 </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">sleep </span></span></font><span>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 <em>SimpleThreads </em>example in a later section.</span></p>
<p class="MyBody"><em><span>Two overloaded versions of sleep are provided</span></em><span>: one that specifies the sleep time to the <strong>millisecond</strong> and one that specifies the sleep time to the <strong>nanosecond</strong>. 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 will suspend the thread for precisely the time period specified. </span></p>
<p class="MyBody"><span>The <em>SleepMessages </em>example uses sleep to print messages at four-second intervals:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> SleepMessages {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String args[]) <strong><span style="color:#7f0055;">throws</span></strong> InterruptedException {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        String importantInfo[] = {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;Mares eat oats&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;Does eat oats&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;Little lambs eat ivy&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;A kid will eat ivy too&#8221;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        };</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">for</span></strong> (<strong><span style="color:#7f0055;">int</span></strong> i = 0; i &lt; importantInfo.<span style="color:#0000c0;">length</span>; i++) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#3f7f5f;">//Pause for 4 seconds</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            Thread.<em>sleep</em>(4000);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#3f7f5f;">//Print a message</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            System.<em><span style="color:#0000c0;">out</span></em>.println(importantInfo[i]);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>Notice that main declares that it throws </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><span>. This is an exception that </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">sleep </span></span></font><span>throws when another thread interrupts the current thread while </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">sleep </span></span></font><span>is active. Since this application has not defined another thread to cause the interrupt, it doesn&#8217;t bother to catch </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><span>.</span></p>
<h3><font color="#666666"><span>Interrupts</span></font></h3>
<p class="MyBody"><span>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. </span></p>
<p class="MyBody"><span>A thread sends an interrupt by invoking <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#interrupt%28%29">interrupt</a> 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. </span></p>
<h3><font size="2"><span>Supporting Interruption</span></font></h3>
<p class="MyBody"><span>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 </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><span>, </span><span>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: </span></p>
<p><span style="color:black;font-family:'Courier New';"><br /></span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">for</span></strong> (<strong><span style="color:#7f0055;">int</span></strong> i = 0; i &lt; importantInfo.length; i++) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <span style="color:#3f7f5f;">//Pause for 4 seconds</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        Thread.sleep(4000);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    } <strong><span style="color:#7f0055;">catch</span></strong> (InterruptedException e) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#3f7f5f;">//We&#8217;ve been interrupted: no more messages.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <span style="color:#3f7f5f;">//Print a message</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    System.out.println(importantInfo[i]);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>Many methods that throw </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><span>, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received. </span></p>
<p class="MyBody"><span>What if a thread goes a long time without invoking a method that throws </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><span>? Then it must periodically invoke </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread.interrupted</span></span></font><span>, which returns true if an interrupt has been received. For example:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">for</span></strong> (<strong><span style="color:#7f0055;">int</span></strong> i = 0; i &lt; inputs.length; i++) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    heavyCrunch(inputs[i]);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">if</span></strong> (Thread.interrupted()) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#3f7f5f;">//We&#8217;ve been interrupted: no more crunching.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>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 </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException:</span></span></font></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">if</span></strong> (Thread.interrupted()) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">throw</span></strong> <strong><span style="color:#7f0055;">new</span></strong> InterruptedException();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>This allows interrupt handling code to be centralized in a catch clause. </span></p>
<h3><font size="2"><span>The Interrupt Status Flag</span></font></h3>
<p style="text-align:left;"><span>The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking </span><font color="#993399"><span style="font-size:11pt;">Thread.interrupt</span></font> <span>sets this flag. When a thread checks for an interrupt by invoking the static method </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread.interrupted</span></span></font><span>, interrupt status is cleared. The non-static </span><font color="#993399"><span style="font-size:11pt;">Thread.isInterrupted</span></font><span style="font-family:Symbol;">,<span style="font-family:Verdana;"> which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.</span></p>
<p></span></p>
<ul>
<li><font color="#993399"><span style="font-size:11pt;">Thread.interrupt</span></font> <span>- thread&#8217;s interrupt status is set</span></li>
</ul>
<ul>
<li><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread.interrupted</span></span></font> <span>- tests whether the current thread has been interrupted.  The interrupted status of the thread is cleared by this method.</span></li>
</ul>
<ul>
<li><font color="#993399"><span style="font-size:11pt;">Thread.isInterrupted</span></font> <span>- tests whether this thread has been interrupted.  The interrupted status of the thread is unaffected by this method.</span></li>
</ul>
<p class="MyBody"><em><span><br />
</span></em></p>
<p class="MyBody"><em><span>By convention, any method that exits by throwing an </span></em><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException </span></span></font><em><span>clears interrupt status when it does so</span></em><span>. However, it&#8217;s always possible that interrupt status will immediately be set again, by another thread invoking interrupt. </span></p>
<h3><font size="2"><span>Joins</span></font></h3>
<p class="MyBody"><em><span>The join method allows one thread to wait for the completion of another.</span></em><span> If it is a Thread object whose thread is currently executing,</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCode">t.join();</p>
<p class="MyBody"><em><span><br />
</span></em></p>
<p class="MyBody"><em><span>Causes the current thread to pause execution until its thread terminates. </span></em><span>Overloads of <font color="#993399"><span style="font-family:Courier New;">join </span></font>allow the programmer to specify a waiting period. However, as with <font color="#993399"><span style="font-family:Courier New;">sleep</span></font>, </span><span><font color="#993399"><span style="font-family:Courier New;">join </span></font></span><span>is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify. </span></p>
<p class="MyBody"><span>Like sleep, join responds to an interrupt by exiting with an </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><em><span>.</span></em></p>
<h3><font size="2"><span>The SimpleThreads Example</span></font></h3>
<p class="MyBody"><span>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 <font color="#993399"><span style="font-family:Courier New;">Runnable </span></font>object, MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it. </span></p>
<p class="MyBody"><span>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.</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> SimpleThreads {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <span style="color:#3f7f5f;">//Display a message, preceded by the name of the current thread</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> threadMessage(String message) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        String threadName = Thread.<em>currentThread</em>().getName();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;%s: %s%n&#8221;</span>, threadName, message);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">class</span></strong> MessageLoop <strong><span style="color:#7f0055;">implements</span></strong> Runnable {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            String importantInfo[] = {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#2a00ff;">&#8220;Mares eat oats&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#2a00ff;">&#8220;Does eat oats&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#2a00ff;">&#8220;Little lambs eat ivy&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#2a00ff;">&#8220;A kid will eat ivy too&#8221;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            };</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <strong><span style="color:#7f0055;">for</span></strong> (<strong><span style="color:#7f0055;">int</span></strong> i = 0; i &lt; importantInfo.<span style="color:#0000c0;">length</span>; i++) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <span style="color:#3f7f5f;">//Pause for 4 seconds</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    Thread.<em>sleep</em>(4000);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <span style="color:#3f7f5f;">//Print a message</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <em>threadMessage</em>(importantInfo[i]);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            } <strong><span style="color:#7f0055;">catch</span></strong> (InterruptedException e) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <em>threadMessage</em>(<span style="color:#2a00ff;">&#8220;I wasn&#8217;t done!&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String args[]) <strong><span style="color:#7f0055;">throws</span></strong> InterruptedException {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#3f7f5f;">//Delay, in milliseconds before we interrupt MessageLoop</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#3f7f5f;">//thread (default one hour).</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">long</span></strong> patience = 1000 * 60 * 60;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#3f7f5f;">//If command line argument present, gives patience in seconds.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">if</span></strong> (args.<span style="color:#0000c0;">length</span> &gt; 0) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                patience = Long.<em>parseLong</em>(args[0]) * 1000;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            } <strong><span style="color:#7f0055;">catch</span></strong> (NumberFormatException e) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                System.<em><span style="color:#0000c0;">err</span></em>.println(<span style="color:#2a00ff;">&#8220;Argument must be an integer.&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                System.<em>exit</em>(1);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <em>threadMessage</em>(<span style="color:#2a00ff;">&#8220;Starting MessageLoop thread&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">long</span></strong> startTime = System.<em>currentTimeMillis</em>();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        Thread t = <strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> MessageLoop());</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        t.start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <em>threadMessage</em>(<span style="color:#2a00ff;">&#8220;Waiting for MessageLoop thread to finish&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#3f7f5f;">//loop until MessageLoop thread exits</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">while</span></strong> (t.isAlive()) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <em>threadMessage</em>(<span style="color:#2a00ff;">&#8220;Still waiting&#8230;&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#3f7f5f;">//Wait maximum of 1 second for MessageLoop thread to</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#3f7f5f;">//finish.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            t.join(1000);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">if</span></strong> (((System.<em>currentTimeMillis</em>() &#8211; startTime) &gt; patience) &amp;&amp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    t.isAlive()) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <em>threadMessage</em>(<span style="color:#2a00ff;">&#8220;Tired of waiting!&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                t.interrupt();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#3f7f5f;">//Shouldn&#8217;t be long now &#8212; wait indefinitely</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                t.join();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <em>threadMessage</em>(<span style="color:#2a00ff;">&#8220;Finally!&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p><span style="font-size:16pt;color:#0033cc;font-family:Georgia;"><br /></span></p>
<h2><font color="#006600"><span>Synchronization</span></font></h2>
<p class="MyBody"><span>Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization. </span></p>
<h3><font color="#666666"><span>Thread Interference</span></font></h3>
<p class="MyBody"><span>Consider a simple class called Counter</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">class</span></strong> Counter {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> c = 0;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> increment() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        c++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> decrement() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        c&#8211;;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">int</span></strong> value() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> c;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>Counter is designed so that each invocation of increment will add 1 to c, and each invocation of decrement will subtract 1 from c. However, if a Counter object is referenced from multiple threads, interference between threads may prevent this from happening as expected. </span></p>
<p class="MyBody"><span>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. </span></p>
<p class="MyBody"><span>It might not seem possible for operations on instances of Counter to interleave, since both operations on c are single, simple statements. However<em>, even simple statements can translate to multiple steps by the virtual machine</em>. We won&#8217;t examine the specific steps the virtual machine takes — it is enough to know that the single expression c++ can be decomposed into three steps:</span></p>
<p class="MyBody"><span><br />
</span></p>
<ol>
<li><span>Retrieve the current value of c. </span></li>
<li><span>Increment the retrieved value by 1. </span></li>
<li><span>Store the incremented value back in c.</span></li>
</ol>
<p><span><br />
</span></p>
<p class="MyBody"><span>The expression c&#8211; can be decomposed the same way, except that the second step decrements instead of increments. </span></p>
<p class="MyBody"><span>Suppose Thread A invokes increment at about the same time Thread B invokes decrement. If the initial value of c is 0, their interleaved actions might follow this sequence:</span></p>
<p class="MyBody"><span><br />
</span></p>
<ol>
<li><span>Thread A: Retrieve c. </span></li>
<li><span>Thread B: Retrieve c. </span></li>
<li><span>Thread A: Increment retrieved value; result is 1. </span></li>
<li><span>Thread B: Decrement retrieved value; result is -1. </span></li>
<li><span>Thread A: Store result in c; c is now 1. </span></li>
<li><span>Thread B: Store result in c; c is now -1. </span></li>
<li><span>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.</span></li>
</ol>
<p><span><br />
</span></p>
<h3><font color="#666666"><span>Memory Consistency Errors</span></font></h3>
<p class="MyBody"><span>Memory consistency errors 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. </span></p>
<p class="MyBody"><span>The key to avoiding memory consistency errors is understanding the <strong>happens-before relationship</strong>. <font color="#cc0000"><strong><em>This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement.</em></strong></font> To see this, consider the following example. Suppose a simple int field is defined and initialized:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeLine"><font color="#990000"><strong>int </strong></font>counter = 0;</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>The counter field is shared between two threads, A and B. Suppose thread A increments counter:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeLine">counter++;</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>Then, shortly afterwards, thread B prints out counter:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeLine">System.out.println(counter);</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>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 t<em>here&#8217;s no guarantee that thread A&#8217;s change to counter will be visible to thread B</em> — unless the programmer has established a happens-before relationship between these two statements. </span></p>
<p class="MyBody"><span>There are several actions that create happens-before relationships. One of them is synchronization, as we will see in the following sections. </span></p>
<p class="MyBody"><span>We&#8217;ve already seen two actions that create happens-before relationships. </span></p>
<p class="MyBody"><span>When a statement invokes </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread.start</span></span></font><span>, 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. </span></p>
<p class="MyBody"><span>When a thread terminates and causes a </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">Thread.join</span></span></font><span> 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 <font color="#993399"><span style="font-family:Courier New;">join</span></font>. The effects of the code in the thread are now visible to the thread that performed the join. </span></p>
<h3><font color="#666666"><span>Synchronized Methods</span></font></h3>
<p class="MyBody"><span>The Java programming language provides two basic synchronization idioms: <em>synchronized methods</em> and <em>synchronized statements</em>. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods. </span></p>
<p class="MyBody"><span>To make a method synchronized, simply add the synchronized keyword to its declaration:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> SynchronizedCounter {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">c</span> = 0;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> increment() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">c</span>++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> decrement() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">c</span>&#8211;;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">int</span></strong> value() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> <span style="color:#0000c0;">c</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects: </span></p>
<p class="MyBody"><span>First, <em>it is <strong>not</strong> possible for two invocations of synchronized methods on the same object to interleave</em>. 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. </span></p>
<p class="MyBody"><span>Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. </span></p>
<p class="MyBody"><span>Note that <strong>constructors cannot be synchronized</strong> — using the <font color="#993399">synchronized </font>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. </span></p>
<p class="MyBody"><span>Warning:  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 List called instances containing every instance of class. You might be tempted to add the line</span></p>
<p class="MyBody"><em><span><br />
</span></em></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeLine">instances.add(this);</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>to your constructor. But then other threads can use instances to access the object before construction of the object is complete. </span></p>
<p class="MyBody"><span>Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: <em>if an object is visible to more than one thread, all reads or writes to that object&#8217;s variables are done through synchronized methods.</em> This strategy is effective, but can present problems with liveness, as we&#8217;ll see later in this lesson. </span></p>
<h3><font color="#666666"><span>Intrinsic Locks and Synchronization</span></font></h3>
<p class="MyBody"><span>Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (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. </span></p>
<p class="MyBody"><span>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 acquire the object&#8217;s intrinsic lock before accessing them, and then release the intrinsic lock when it&#8217;s done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. 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. </span></p>
<p class="MyBody"><span>When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock. </span></p>
<h3><font size="2" color="#000000"><span>Locks in Synchronized Methods</span></font></h3>
<p class="MyBody"><span>When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method&#8217;s object and releases it when the method returns. <em>The lock release occurs even if the return was caused by an uncaught exception.</em> </span></p>
<p class="MyBody"><span>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 Class 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. </span></p>
<h3><font size="4" color="#666666"><span>Synchronized Statements</span></font></h3>
<p class="MyBody"><span>Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements <strong>must specify the object</strong> that provides the intrinsic lock:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> addName(String name) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">synchronized</span></strong>(<strong><span style="color:#7f0055;">this</span></strong>) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        lastName = name;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        nameCount++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    nameList.add(name);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects&#8217; methods. (Invoking other objects&#8217; methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking </span><span style="font-size:11pt;">nameList.add</span><span>. </span></p>
<p class="MyBody"><span>Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, 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 this, we create two objects solely to provide locks.</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> MsLunch {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">long</span></strong> <span style="color:#0000c0;">c1</span> = 0;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">long</span></strong> <span style="color:#0000c0;">c2</span> = 0;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> Object <span style="color:#0000c0;">lock1</span> = <strong><span style="color:#7f0055;">new</span></strong> Object();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> Object <span style="color:#0000c0;">lock2</span> = <strong><span style="color:#7f0055;">new</span></strong> Object();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> inc1() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">synchronized</span></strong>(<span style="color:#0000c0;">lock1</span>) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#0000c0;">c1</span>++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">   </p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> inc2() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">synchronized</span></strong>(<span style="color:#0000c0;">lock2</span>) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#0000c0;">c2</span>++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields. </span></p>
<h3><font color="#666666"><span>Reentrant Synchronization</span></font></h3>
<p class="MyBody"><span>Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. <strong><em>Allowing a thread to acquire the same lock more than once enables reentrant synchronization.</em></strong> 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. </span></p>
<h3><font size="2"><span>Atomic Access</span></font></h3>
<p class="MyBody"><span>In programming, an atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn&#8217;t happen at all. <em>No side effects of an atomic action are visible until the action is complete.</em> </span></p>
<p class="MyBody"><span>We&#8217;ve already seen that an increment expression, such as c++, does not describe an atomic action. Even very simple expressions can define complex actions that can decompose into other actions.</span></p>
<p class="MyListCxSpFirst"><em><span>However, there are actions you can specify that are atomic:</span></em></p>
<p class="MyListCxSpFirst">&nbsp;</p>
<ul>
<li><span>Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double). </span></li>
</ul>
<ul>
<li><span>Reads and writes are atomic for all variables declared volatile (including long and double variables).</span></li>
</ul>
<p><span><br />
</span></p>
<p class="MyBody"><em><span>Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.</span></em><span> This means that <em>changes to a volatile variable are always visible to other threads</em>. What&#8217;s more, <em>it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change. </em></span></p>
<p class="MyBody"><span>Using simple atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors. Whether the extra effort is worthwhile depends on the size and complexity of the application. </span></p>
<p class="MyBody"><span>Some of the classes in the </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">java.util.concurrent</span></span></font> <span>packages provide atomic methods that do not rely on synchronization. </span></p>
<h3><font color="#666666"><span>Liveness</span></font></h3>
<p class="MyBody"><em><span>A concurrent application&#8217;s ability to execute in a timely manner is known as its liveness.</span></em><span> This section describes the most common kind of liveness problem, deadlock, and goes on to briefly describe two other liveness problems, starvation and livelock. </span></p>
<h3><font size="2"><span>Deadlock</span></font></h3>
<p class="MyBody"><span>Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here&#8217;s an example. </span></p>
<p class="MyBody"><span>Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time. This example application, Deadlock, models this possibility:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> Deadlock {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">class</span></strong> Friend {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">final</span></strong> String <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">public</span></strong> Friend(String name) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span> = name;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">public</span></strong> String getName() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  <strong><span style="color:#7f0055;">return</span></strong> <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> bow(Friend bower) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;%s: %s has bowed to me!%n&#8221;</span>, <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>, bower.getName());</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  bower.bowBack(<strong><span style="color:#7f0055;">this</span></strong>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> bowBack(Friend bower) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;%s: %s has bowed back to me!%n&#8221;</span>, <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>, bower.getName());</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String[] args) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">final</span></strong> Friend alphonse = <strong><span style="color:#7f0055;">new</span></strong> Friend(<span style="color:#2a00ff;">&#8220;Alphonse&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">final</span></strong> Friend gaston = <strong><span style="color:#7f0055;">new</span></strong> Friend(<span style="color:#2a00ff;">&#8220;Gaston&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> Runnable() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                        alphonse.bow(gaston);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> Runnable() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                        gaston.bow(alphonse);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                  }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>When Deadlock runs, it&#8217;s extremely likely that both threads will block when they attempt to invoke </span><font size="2"><span style="font-family:Verdana;" class="MyCodeLineCharChar"><span style="font-size:11pt;">bowBack</span></span></font><span><font size="2">. </font>Neither block will ever end, because each thread is waiting for the other to exit bow. </span></p>
<h3><font size="2"><span>Starvation and Livelock</span></font></h3>
<p class="MyBody"><span>Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter. </span></p>
<h3><font size="2" color="#6666cc"><span>Starvation</span></font></h3>
<p class="MyBody"><span>Starvation describes <em>a situation where a thread is unable to gain regular access to shared resources and is unable to make progress</em>. This happens when shared resources are made unavailable for long periods by &#8220;greedy&#8221; threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. </span></p>
<h3><font size="2" color="#6666cc"><span>Livelock</span></font></h3>
<p class="MyBody"><span>A thread often acts in response to the action of another thread. If the other thread&#8217;s action is also a response to the action of another thread, then livelock may result. <em>As with deadlock, livelocked threads are unable to make further progress. </em>However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left. They&#8217;re still blocking each other, so&#8230; </span></p>
<h3><font size="2" color="#6666cc"><span>Guarded Blocks</span></font></h3>
<p class="MyBody"><span>Threads often have to coordinate their actions. The most common coordination idiom is the guarded block. <em>Such a block begins by polling a condition that must be true before the block can proceed. </em>There are a number of steps to follow in order to do this correctly. </span></p>
<p class="MyBody"><span>Suppose, for example guardedJoy is a method that must not proceed until a shared variable joy has been set by another thread. Such a method could, in theory, simply loop until the condition is satisfied, but that loop is wasteful, since it executes continuously while waiting. </span></p>
<p><span style="color:black;font-family:'Courier New';"><br /></span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> guardedJoy() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <span style="color:#3f7f5f;">//Simple loop guard. Wastes processor time. Don&#8217;t do this!</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">while</span></strong>(!joy) {}</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    System.out.println(<span style="color:#2a00ff;">&#8220;Joy has been achieved!&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>A more efficient guard invokes <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait%28%29">Object.wait</a> to suspend the current thread. The invocation of wait does not return until another thread has issued a notification that some special event may have occurred — though not necessarily the event this thread is waiting for:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;"><font color="#663366"><strong>public synchronized</strong></font> guardedJoy() {</p>
<p>   <font color="#006600"> // This guard only loops once for each special event, which may not<br />
    // be the event we&#8217;re waiting for.</font></p>
<p>    <font color="#663366"><strong>while</strong>(!</font>joy) {<br />
        <font color="#663366"><strong>try </strong></font>{<br />
            wait();<br />
        } <font color="#663366"><strong>catch </strong></font>(InterruptedException e) {}<br />
    }<br />
    System.out.println(&#8220;<font color="#3333ff">Joy and efficiency have been achieved!</font>&#8220;);<br />
}</p>
<p class="MyBody"><em><span><br />
</span></em></p>
<p class="MyBody"><em><span>Note: Always invoke wait inside a loop that tests for the condition being waited for. Don&#8217;t assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true. </span></em></p>
<p class="MyBody"><span>Like many methods that suspend execution, </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">wait</span></span></font> <span>can throw </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">InterruptedException</span></span></font><span>. In this example, we can just ignore that exception — we only care about the value of joy. </span></p>
<p class="MyBody"><span>Why is this version of guardedJoy synchronized? Suppose d is the object we&#8217;re using to invoke </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">wait</span></span></font><span>. When a thread invokes </span><span style="font-size:11pt;">d.wait</span><span>, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock. </span></p>
<p class="MyBody"><span>When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29">Object.notifyAll</a>, informing all threads waiting on that lock that something important has happened:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpFirst"><font color="#660000"><strong>public synchronized</strong></font> <span style="color:black;">notifyJoy() {</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    joy = </span>true<span style="color:black;">;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    notifyAll();</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpLast"><span style="color:black;">}</span></p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of wait. </span></p>
<p class="MyBody"><em><span>Note: There is a second notification method, notify, which wakes up a single thread. Because notify doesn&#8217;t allow you to specify the thread that is woken up, it is useful only in massively parallel applications — that is, programs with a large number of threads, all doing similar chores. In such an application, you don&#8217;t care which thread gets woken up. </span></em></p>
<p class="MyBody"><span>Let&#8217;s use guarded blocks to create a Producer-Consumer application. This kind of application shares data between two threads: the producer that creates the data, and the consumer, that does something with it. The two threads communicate using a shared object. Coordination is essential: the consumer thread must not attempt to retrieve the data before the producer thread has delivered it, and the producer thread must not attempt to deliver new data if the consumer hasn&#8217;t retrieved the old data. </span></p>
<p class="MyBody"><span>In this example, the data is a series of text messages, which are shared through an object of type Drop:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpFirst"><strong><span style="color:#7f0055;"><font size="2">public class</font></span></strong><span style="color:black;"> Drop {</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><span style="color:#3f7f5f;">//Message sent from producer to consumer.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><strong><span style="color:#7f0055;"><font size="2">private</font></span></strong><span style="color:black;"> String </span><span style="color:#0000c0;">message</span><span style="color:black;">;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><span style="color:#3f7f5f;">//True if consumer should wait for producer to send message, false</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><span style="color:#3f7f5f;">//if producer should wait for consumer to retrieve message.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><strong><span style="color:#7f0055;"><font size="2">private</font></span></strong> <strong><span style="color:#7f0055;"><font size="2">boolean</font></span></strong> <span style="color:#0000c0;">empty</span><span style="color:black;"> = </span><strong><span style="color:#7f0055;"><font size="2">true</font></span></strong><span style="color:black;">;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><strong><span style="color:#7f0055;"><font size="2">public</font></span></strong> <strong><span style="color:#7f0055;"><font size="2">synchronized</font></span></strong><span style="color:black;"> String take(){</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Wait until message is available.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><strong><span style="color:#7f0055;"><font size="2">while</font></span></strong><span style="color:black;"> (</span><span style="color:#0000c0;">empty</span><span style="color:black;">) {</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">            </span><strong><span style="color:#7f0055;"><font size="2">try</font></span></strong><span style="color:black;"> {</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">                wait();</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">            } </span><strong><span style="color:#7f0055;"><font size="2">catch</font></span></strong><span style="color:black;"> (</span><span style="color:blue;">InterruptedException</span><span style="color:black;"> e) {}</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        }</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Toggle status.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#0000c0;">empty</span><span style="color:black;"> = </span><strong><span style="color:#7f0055;"><font size="2">true</font></span></strong><span style="color:black;">;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Notify producer that status has changed.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        notifyAll();</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><strong><span style="color:#7f0055;"><font size="2">return</font></span></strong> <span style="color:#0000c0;">message</span><span style="color:black;">;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    }</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    </span><strong><span style="color:#7f0055;"><font size="2">public synchronized void</font></span></strong><span style="color:black;"> put(String message) {</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Wait until message has been retrieved.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><strong><span style="color:#7f0055;"><font size="2">while</font></span></strong><span style="color:black;"> (!</span><span style="color:#0000c0;">empty</span><span style="color:black;">) {</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">            </span><strong><span style="color:#7f0055;"><font size="2">try</font></span></strong><span style="color:black;"> { </span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">                wait();</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">            } </span><strong><span style="color:#7f0055;"><font size="2">catch</font></span></strong><span style="color:black;"> (InterruptedException e) {}</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        }</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Toggle status.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#0000c0;">empty</span><span style="color:black;"> = </span><strong><span style="color:#7f0055;"><font size="2">false</font></span></strong><span style="color:black;">;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Store message.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><strong><span style="color:#7f0055;"><font size="2">this</font></span></strong><span style="color:black;">.</span><span style="color:#0000c0;">message</span><span style="color:black;"> = message;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        </span><span style="color:#3f7f5f;">//Notify consumer that status has changed.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">        notifyAll();</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpMiddle"><span style="color:black;">    }</span></p>
<p style="border:medium none;padding:0;" class="MyCodeLineCxSpLast"><span style="color:black;">}</span></p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>The producer thread, defined in Producer, sends a series of familiar messages. The string &#8220;DONE&#8221; indicates that all messages have been sent. To simulate the unpredictable nature of real-world applications, the producer thread pauses for random intervals between messages.</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">import</span></strong> java.util.Random;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> Producer <strong><span style="color:#7f0055;">implements</span></strong> Runnable {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> Drop drop;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> Producer(Drop drop) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.drop = drop;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        String importantInfo[] = {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;Mares eat oats&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;Does eat oats&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;Little lambs eat ivy&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#2a00ff;">&#8220;A kid will eat ivy too&#8221;</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        };</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        Random random = <strong><span style="color:#7f0055;">new</span></strong> Random();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">for</span></strong> (<strong><span style="color:#7f0055;">int</span></strong> i = 0; i &lt; importantInfo.<span style="color:#0000c0;">length</span>; i++) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            drop.put(importantInfo[i]);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                Thread.<em>sleep</em>(random.nextInt(5000));</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            } <strong><span style="color:#7f0055;">catch</span></strong> (InterruptedException e) {}</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        drop.put(<span style="color:#2a00ff;">&#8220;DONE&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>The consumer thread, defined in Consumer, simply retrieves the messages and prints them out, until it retrieves the &#8220;DONE&#8221; string. This thread also pauses for random intervals.</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">import</span></strong> java.util.Random;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> Consumer <strong><span style="color:#7f0055;">implements</span></strong> Runnable {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> Drop drop;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> Consumer(Drop drop) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.drop = drop;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <font color="#663366"><strong><span style="color:#7f0055;">public</span></strong> </font><strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        Random random = <strong><span style="color:#7f0055;">new</span></strong> Random();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">for</span></strong> (String message = drop.take(); ! message.equals(<span style="color:#2a00ff;">&#8220;DONE&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                message = drop.take()) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;MESSAGE RECEIVED: %s%n&#8221;</span>, message);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                Thread.<em>sleep</em>(random.nextInt(5000));</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            } <strong><span style="color:#7f0055;">catch</span></strong> (InterruptedException e) {}</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}               </p>
<p class="MyBody">&nbsp;</p>
<p class="MyBody"><span>Finally, here is the main thread, defined in ProducerConsumerExample, that launches the producer and consumer threads.</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> ProducerConsumerExample {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String[] args) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        Drop drop = <strong><span style="color:#7f0055;">new</span></strong> Drop();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        (<strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> Producer(drop))).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        (<strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> Consumer(drop))).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><em><span><br />
</span></em></p>
<p class="MyBody"><em><span>Note: The Drop class was written in order to demonstrate guarded blocks. To avoid re-inventing the wheel, examine the existing data structures in the <a target="_top" href="http://java.sun.com/docs/books/tutorial/collections/index.html">Java Collections Framework</a> before trying to code your own data-sharing objects.<br />
</span></em></p>
<h2><font color="#006600"><span>Immutable Objects</span></font></h2>
<p class="MyBody"><span>An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. </span></p>
<p class="MyBody"><span>Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. </span></p>
<p class="MyBody"><span>Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption. </span></p>
<p class="MyBody"><span>The following subsections take a class whose instances are mutable and derive a class with immutable instances from it. In so doing, they give general rules for this kind of conversion and demonstrate some of the advantages of immutable objects. </span></p>
<h3><font size="2"><span>A Synchronized Class Example</span></font></h3>
<p class="MyBody"><span>The class, SynchronizedRGB, defines objects that represent colors. Each object represents the color as three integers that stand for primary color values and a string that gives the name of the color.</span></p>
<p><span style="color:black;font-family:'Courier New';"><br /></span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> SynchronizedRGB {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <span style="color:#3f7f5f;">//Values must be between 0 and 255.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">red</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">green</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">blue</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> String <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">void</span></strong> check(<strong><span style="color:#7f0055;">int</span></strong> red, <strong><span style="color:#7f0055;">int</span></strong> green, <strong><span style="color:#7f0055;">int</span></strong> blue) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">if</span></strong> (red &lt; 0 || red &gt; 255</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                || green &lt; 0 || green &gt; 255</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                || blue &lt; 0 || blue &gt; 255) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">throw</span></strong> <strong><span style="color:#7f0055;">new</span></strong> IllegalArgumentException();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> SynchronizedRGB(<strong><span style="color:#7f0055;">int</span></strong> red, <strong><span style="color:#7f0055;">int</span></strong> green, <strong><span style="color:#7f0055;">int</span></strong> blue, String name) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        check(red, green, blue);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">red</span> = red;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">green</span> = green;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">blue</span> = blue;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span> = name;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> set(<strong><span style="color:#7f0055;">int</span></strong> red, <strong><span style="color:#7f0055;">int</span></strong> green, <strong><span style="color:#7f0055;">int</span></strong> blue, String name) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        check(red, green, blue);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">synchronized</span></strong> (<strong><span style="color:#7f0055;">this</span></strong>) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">red</span> = red;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">green</span> = green;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">blue</span> = blue;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span> = name;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">int</span></strong> getRGB() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> ((<span style="color:#0000c0;">red</span> &lt;&lt; 16) | (<span style="color:#0000c0;">green</span> &lt;&lt; 8) | <span style="color:#0000c0;">blue</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> String getName() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> invert() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">red</span> = 255 &#8211; <span style="color:#0000c0;">red</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">green</span> = 255 &#8211; <span style="color:#0000c0;">green</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">blue</span> = 255 &#8211; <span style="color:#0000c0;">blue</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">name</span> = <span style="color:#2a00ff;">&#8220;Inverse of &#8220;</span> + <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>SynchronizedRGB must be used carefully to avoid being seen in an inconsistent state. Suppose, for example, a thread executes the following code: </span></p>
<p><span style="color:black;font-family:'Courier New';"><br /></span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst">SynchronizedRGB color = <strong><span style="color:#7f0055;">new</span></strong> SynchronizedRGB(0, 0, 0, &#8220;<span style="color:#2a00ff;">Pitch Black</span>&#8220;);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&#8230;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">int</span></strong> myColorInt = color.getRGB();      <span style="color:#3f7f5f;">//Statement 1</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">String myColorName = color.getName(); <span style="color:#3f7f5f;">//Statement 2</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><span style="color:#3f7f5f;">//If another thread invokes color.set after Statement 1 but before Statement 2, the value of myColorInt won&#8217;t match the value of myColorName. To avoid this outcome, the two statements must be bound together: </span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">synchronized</span></strong> (color) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">int</span></strong> myColorInt = color.getRGB();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    String myColorName = color.getName();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><span>This kind of inconsistency is only possible for mutable objects — it will not be an issue for the immutable version of SynchronizedRGB. </span></p>
<h2><font size="2"><span>A Strategy for Defining Immutable Objects</span></font></h2>
<p class="MyBody"><span>The following rules define a simple strategy for creating immutable objects. Not all classes documented as &#8220;immutable&#8221; follow these rules. This does not necessarily mean the creators of these classes were sloppy — they may have good reason for believing that instances of their classes never change after construction. However, such strategies require sophisticated analysis and are not for beginners. </span></p>
<p class="MyBody"><span>Don&#8217;t provide &#8220;setter&#8221; methods — methods that modify fields or objects referred to by fields.</span></p>
<p class="MyBody"><span><br />
</span></p>
<p class="MyBody"><strong><span>Make all fields final and private.</span></strong></p>
<ul>
<li><span>Don&#8217;t allow subclasses to override methods.</span></li>
</ul>
<ul>
<li><span>The simplest way to do this is to declare the class as final.</span></li>
</ul>
<ul>
<li><span>A more sophisticated approach is to make the constructor private and construct instances in factory methods. </span></li>
</ul>
<p><em><span>If the instance fields include references to mutable objects, don&#8217;t allow those objects to be changed:</p>
<p></span></em></p>
<p class="MyBody"><strong><span>Don&#8217;t provide methods that modify the mutable objects. </span></strong></p>
<ul>
<li><span>Don&#8217;t share references to the mutable objects.</span></li>
</ul>
<ul>
<li><span>Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.</span></li>
</ul>
<ul>
<li><span>Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. </span></li>
</ul>
<p><span style="font-family:'Times New Roman';"><br /></span></p>
<p class="MyBody"><span>Applying this strategy to SynchronizedRGB results in the following steps: </span></p>
<ul>
<li><span>There are two setter methods in this class. The first one, set, arbitrarily transforms the object, and has no place in an immutable version of the class. The second one, invert, can be adapted by having it create a new object instead of modifying the existing one. </span></li>
</ul>
<ul>
<li><span>All fields are already private; they are further qualified as final. </span></li>
</ul>
<ul>
<li><span>The class itself is declared final. </span></li>
</ul>
<p class="MyListCxSpLast"><span>Only one field refers to an object, and that object is itself immutable. Therefore, no safeguards against changing the state of &#8220;contained&#8221; mutable objects are necessary. </span></p>
<p class="MyBody"><span>After these changes, we have ImmutableRGB:</span></p>
<p class="MyBody"><span><br />
</span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">final</span></strong> <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> ImmutableRGB {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <span style="color:#3f7f5f;">//Values must be between 0 and 255.</span></p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">final</span></strong> <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">red</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">final</span></strong> <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">green</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">final</span></strong> <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">blue</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">final</span></strong> <strong><span style="color:#7f0055;">private</span></strong> String <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">void</span></strong> check(<strong><span style="color:#7f0055;">int</span></strong> red, <strong><span style="color:#7f0055;">int</span></strong> green, <strong><span style="color:#7f0055;">int</span></strong> blue) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">if</span></strong> (<u><span style="color:blue;">red</span></u> &lt; 0 || red &gt; 255</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                || green &lt; 0 || green &gt; 255</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                || blue &lt; 0 || blue &gt; 255) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">throw</span></strong> <strong><span style="color:#7f0055;">new</span></strong> IllegalArgumentException();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> ImmutableRGB(<strong><span style="color:#7f0055;">int</span></strong> red, <strong><span style="color:#7f0055;">int</span></strong> green, <strong><span style="color:#7f0055;">int</span></strong> blue, String name) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        check(red, green, blue);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">red</span> = red;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">green</span> = green;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">blue</span> = blue;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span> = name;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">int</span></strong> getRGB() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> ((<span style="color:#0000c0;">red</span> &lt;&lt; 16) | (<span style="color:#0000c0;">green</span> &lt;&lt; 8) | <span style="color:#0000c0;">blue</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> String getName() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> ImmutableRGB invert() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> <strong><span style="color:#7f0055;">new</span></strong> ImmutableRGB(255 &#8211; <span style="color:#0000c0;">red</span>, 255 &#8211; <span style="color:#0000c0;">green</span>, 255 &#8211; <span style="color:#0000c0;">blue</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#2a00ff;">&#8220;Inverse of &#8220;</span> + <span style="color:#0000c0;">name</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyHeading"><span><br />
</span></p>
<h2><font color="#006600"><span>High Level Concurrency Objects</span></font></h2>
<p class="MyBody"><span>So far, this lesson has focused on the low-level APIs that have been part of the Java platform from the very beginning. These APIs are adequate for very basic tasks, but higher-level building blocks are needed for more advanced tasks. This is especially true for massively concurrent applications that fully exploit today&#8217;s multiprocessor and multi-core systems. </span></p>
<p class="MyBody"><span>In this section we&#8217;ll look at some of the high-level concurrency features introduced with version 5.0 of the Java platform. Most of these features are implemented in the new </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">java.util.concurrent</span></span></font><span> packages. There are also new concurrent data structures in the Java Collections Framework. </span></p>
<ul>
<li><strong><span>Lock objects</span></strong><span> support locking idioms that simplify many concurrent applications. </span></li>
</ul>
<ul>
<li><strong><span>Executors</span></strong><span> define a high-level API for launching and managing threads. Executor implementations provided by </span><span style="font-size:11pt;">java.util.concurrent</span><span> provide thread pool management suitable for large-scale applications. </span></li>
</ul>
<ul>
<li><strong><span>Concurrent collections</span></strong><span> make it easier to manage large collections of data, and can greatly reduce the need for synchronization. </span></li>
</ul>
<ul>
<li><strong><span>Atomic variables</span></strong><span> have features that minimize synchronization and help avoid memory consistency errors.</span></li>
</ul>
<h3><font size="2"><span>Lock Objects</span></font></h3>
<p class="MyBody"><span>Synchronized code relies on a simple kind of reentrant lock. This kind of lock is easy to use, but has many limitations. More sophisticated locking idioms are supported by the </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">java.util.concurrency.locks</span></span></font><span> package. We won&#8217;t examine this package in detail, but instead will focus on its most basic interface, <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html">Lock</a>. </span></p>
<p class="MyBody"><span>Lock objects work very much like the implicit locks used by synchronized code. As with implicit locks, only one thread can own a Lock object at a time. Lock objects also support a wait/notify mechanism, through their associated <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html">Condition</a> objects. </span></p>
<p class="MyBody"><em><span>The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock.</span></em><span> The </span><font color="#993399"><span style="font-family:Courier New;" class="MyCodeLineCharChar"><span style="font-size:11pt;">tryLock</span></span></font> <span>method backs out if the lock is not available immediately or before a timeout expires (if specified). The </span><font color="#993399"><span style="font-size:11pt;">lockInterruptibly</span></font> <span>method backs out if another thread sends an interrupt before the lock is acquired. </span></p>
<p class="MyBody"><span>Let&#8217;s use Lock objects to solve the deadlock problem we saw in Liveness. Alphonse and Gaston have trained themselves to notice when a friend is about to bow. We model this improvement by requiring that our Friend objects must acquire locks for both participants before proceeding with the bow. Here is the source code for the improved model, Safelock. To demonstrate the versatility of this idiom, we assume that Alphonse and Gaston are so infatuated with their newfound ability to bow safely that they can&#8217;t stop bowing to each other: </span></p>
<p><span style="color:black;font-family:'Courier New';"><br /></span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">import</span></strong> java.util.concurrent.locks.Lock;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">import</span></strong> java.util.concurrent.locks.ReentrantLock;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">import</span></strong> java.util.Random;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">class</span></strong> Safelock {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">class</span></strong> Friend {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">final</span></strong> String <span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">final</span></strong> Lock <span style="color:#0000c0;">lock</span> = <strong><span style="color:#7f0055;">new</span></strong> ReentrantLock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> Friend(String name) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span> = name;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> String getName() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">return</span></strong> <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">boolean</span></strong> impendingBow(Friend bower) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            Boolean myLock = <strong><span style="color:#7f0055;">false</span></strong>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            Boolean yourLock = <strong><span style="color:#7f0055;">false</span></strong>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                myLock = <span style="color:#0000c0;">lock</span>.tryLock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                yourLock = bower.<span style="color:#0000c0;">lock</span>.tryLock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            } <strong><span style="color:#7f0055;">finally</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <strong><span style="color:#7f0055;">if</span></strong> (! (myLock &amp;&amp; yourLock)) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <strong><span style="color:#7f0055;">if</span></strong> (myLock) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                        <span style="color:#0000c0;">lock</span>.unlock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <strong><span style="color:#7f0055;">if</span></strong> (yourLock) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                        bower.<span style="color:#0000c0;">lock</span>.unlock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">return</span></strong> myLock &amp;&amp; yourLock;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">           </p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> bow(Friend bower) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">if</span></strong> (impendingBow(bower)) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;%s: %s has bowed to me!%n&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>, bower.getName());</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    bower.bowBack(<strong><span style="color:#7f0055;">this</span></strong>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                } <strong><span style="color:#7f0055;">finally</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <span style="color:#0000c0;">lock</span>.unlock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    bower.<span style="color:#0000c0;">lock</span>.unlock();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            } <strong><span style="color:#7f0055;">else</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;%s: %s started to bow to me, but&#8221;</span> +</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                        <span style="color:#2a00ff;">&#8221; saw that I was already bowing to him.%n&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                        <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>, bower.getName());</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> bowBack(Friend bower) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            System.<em><span style="color:#0000c0;">out</span></em>.format(<span style="color:#2a00ff;">&#8220;%s: %s has bowed back to me!%n&#8221;</span>,</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">name</span>, bower.getName());</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">class</span></strong> BowLoop <strong><span style="color:#7f0055;">implements</span></strong> Runnable {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">private</span></strong> Friend <span style="color:#0000c0;">bower</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">private</span></strong> Friend <span style="color:#0000c0;">bowee</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> BowLoop(Friend bower, Friend bowee) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">bower</span> = bower;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">this</span></strong>.<span style="color:#0000c0;">bowee</span> = bowee;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">   </p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> run() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            Random random = <strong><span style="color:#7f0055;">new</span></strong> Random();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">for</span></strong> (;;) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <strong><span style="color:#7f0055;">try</span></strong> {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                    Thread.<em>sleep</em>(random.nextInt(10));</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                } <strong><span style="color:#7f0055;">catch</span></strong> (InterruptedException e) {}</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">                <span style="color:#0000c0;">bowee</span>.bow(<span style="color:#0000c0;">bower</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">           </p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">static</span></strong> <strong><span style="color:#7f0055;">void</span></strong> main(String[] args) {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">final</span></strong> Friend alphonse = <strong><span style="color:#7f0055;">new</span></strong> Friend(<span style="color:#2a00ff;">&#8220;Alphonse&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">final</span></strong> Friend gaston = <strong><span style="color:#7f0055;">new</span></strong> Friend(<span style="color:#2a00ff;">&#8220;Gaston&#8221;</span>);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> BowLoop(alphonse, gaston)).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">new</span></strong> Thread(<strong><span style="color:#7f0055;">new</span></strong> BowLoop(gaston, alphonse)).start();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MySubHeading"><span>Executors</span></p>
<p class="MyBody"><span>In all of the previous examples, there&#8217;s a close connection between the task being done by a new thread, as defined by its Runnable object, and the thread itself, as defined by a Thread object. This works well for small applications, but in large-scale applications, it makes sense to separate thread management and creation from the rest of the application. Objects that encapsulate these functions are known as executors. The following subsections describe executors in detail. </span></p>
<p class="MyListCxSpFirst"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><strong><span>Executor Interfaces</span></strong><span> define the three executor object types. </span></p>
<p class="MyListCxSpLast"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><strong><span>Thread Pools</span></strong><span> are the most common kind of executor implementation. </span></p>
<p><strong><span style="font-family:'Times New Roman';"><br /></span></strong></p>
<p class="MyBody"><strong><span>Executor Interfaces</span></strong></p>
<p class="MyBody"><span>The </span><span style="font-size:11pt;">java.util.concurrent</span><span> package defines three executor interfaces: </span></p>
<p class="MyListCxSpFirst"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span style="font-size:11pt;">Executor</span><span>, a simple interface that supports launching new tasks. </span></p>
<p class="MyListCxSpMiddle"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span style="font-size:11pt;">ExecutorService</span><span>, a sub-interface of </span><span style="font-size:11pt;">Executor</span><span>, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself. </span></p>
<p class="MyListCxSpLast"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span style="font-size:11pt;">ScheduledExecutorService</span><span>, a sub-interface of </span><span style="font-size:11pt;">ExecutorService</span><span>, supports future and/or periodic execution of tasks. </span></p>
<p class="MyBody"><span>Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type. </span></p>
<p class="MyBody"><strong><em><span>The Executor Interface</span></em></strong></p>
<p class="MyBody"><span>The </span><span style="font-size:11pt;"><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executor.html"><span style="color:#993366;">Executor</span></a></span><span> interface provides a single method, </span><span style="font-size:11pt;">execute</span><span>, designed to be a drop-in replacement for a common thread-creation idiom. If r is a </span><span style="font-size:11pt;">Runnable</span><span> object, and e is an </span><span style="font-size:11pt;">Executor</span><span> object you can replace </span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCode">(<strong><span style="color:#7f0055;">new</span></strong> Thread(r)).start();</p>
<p class="MyBody"><span>with </span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCode">e.execute(r);</p>
<p class="MyBody"><span>However, the definition of execute is less specific. The low-level idiom creates a new thread and launches it immediately. Depending on the Executor implementation, </span><span style="font-size:11pt;">execute</span><span> may do the same thing, but is more likely to use an existing worker thread to run r, or to place r in a queue to wait for a worker thread to become available. (We&#8217;ll describe worker threads in the section on Thread Pools.) </span></p>
<p class="MyBody"><span>The executor implementations in </span><span style="font-size:11pt;">java.util.concurrent</span><span> are designed to make full use of the more advanced </span><span style="font-size:11pt;">ExecutorService</span><span> and </span><span style="font-size:11pt;">ScheduledExecutorService</span><span> interfaces, although they also work with the base Executor interface. </span></p>
<p class="MyBody"><strong><em><span>The ExecutorService Interface</span></em></strong></p>
<p class="MyBody"><span>The <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html">ExecutorService</a> interface supplements execute with a similar, but more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html">Callable</a> objects, which allow the task to return a value. The submit method returns a <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html">Future</a> object, which is used to retrieve the </span><span style="font-size:11pt;">Callable</span><span> return value and to manage the status of both Callable and Runnable tasks. </span></p>
<p class="MyBody"><span>ExecutorService also provides methods for submitting large collections of Callable objects. Finally, ExecutorService provides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts correctly. </span></p>
<p class="MyBody"><strong><em><span>The ScheduledExecutorService Interface</span></em></strong></p>
<p class="MyBody"><span>The <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html">ScheduledExecutorService</a> interface supplements the methods of its parent ExecutorService with schedule, which executes a Runnable or Callable task after a specified delay. In addition, the interface defines </span><span style="font-size:11pt;">scheduleAtFixedRate</span><span> and </span><span style="font-size:11pt;">scheduleWithFixedDelay</span><span>, which executes specified tasks repeatedly, at defined intervals. </span></p>
<p class="MySubHeading"><span>Thread Pools</span></p>
<p class="MyBody"><span>Most of the executor implementations in </span><span style="font-size:11pt;">java.util.concurrent</span><span> use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks. </span></p>
<p class="MyBody"><span>Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead. </span></p>
<p class="MyBody"><span>One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads. </span></p>
<p class="MyBody"><span>An important advantage of the fixed thread pool is that applications using it degrade gracefully. To understand this, consider a web server application where each HTTP request is handled by a separate thread. If the application simply creates a new thread for every new HTTP request, and the system receives more requests than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system. With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain. </span></p>
<p class="MyBody"><span>A simple way to create an executor that uses a fixed thread pool is to invoke the <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29">newFixedThreadPool</a> factory method in <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html">java.util.concurrent.Executors</a> this class also provides the following factory methods: </span></p>
<p class="MyListCxSpFirst"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span>The <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool%28int%29">newCachedThreadPool</a> method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks. </span></p>
<p class="MyListCxSpLast"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span>The <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor%28int%29">newSingleThreadExecutor</a> method creates an executor that executes a single task at a time. </span></p>
<p class="MyBody"><span>Several factory methods are ScheduledExecutorService versions of the above executors. </span></p>
<p class="MyBody"><span>If none of the executors provided by the above factory methods meet your needs, constructing instances of <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html">java.util.concurrent.ThreadPoolExecutor</a> or <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html">java.util.concurrent.ScheduledThreadPoolExecutor</a> will give you additional options. </span></p>
<p><span style="color:#006600;font-family:Georgia;"><br /></span></p>
<p class="MySubHeading"><span>Concurrent Collections</span></p>
<p class="MyBody"><span>The </span><span style="font-size:11pt;">java.util.concurrent</span><span> package includes a number of additions to the Java Collections Framework. These are most easily categorized by the collection interfaces provided: </span></p>
<p class="MyListCxSpFirst"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html">BlockingQueue</a> defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue. </span></p>
<p class="MyListCxSpMiddle"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentMap.html">ConcurrentMap</a> is a sub-interface of <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/Map.html">java.util.Map</a> that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. Making these operations atomic helps avoid synchronization. The standard general-purpose implementation of ConcurrentMap is <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html">ConcurrentHashMap</a>, which is a concurrent analog of <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html">HashMap</a>. </span></p>
<p class="MyListCxSpLast"><span style="font-family:Wingdings;">ü<span style="font-size:7pt;line-height:normal;font-family:'Times New Roman';font-variant:normal;">      </span></span><span><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentNavigableMap.html">ConcurrentNavigableMap</a> is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap is <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentSkipListMap.html">ConcurrentSkipListMap</a>, which is a concurrent analog of <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html">TreeMap</a>. </span></p>
<p class="MyBody"><span>All of these collections help avoid Memory Consistency Errors by defining a happens-before relationship between an operation that adds an object to the collection with subsequent operations that access or remove that object. </span></p>
<p class="MySubHeading"><span>Atomic Variables</span></p>
<p class="MyBody"><span>The </span><span style="font-size:11pt;"><a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html"><span style="color:#993366;">java.util.concurrent.atomic</span></a></span><span> package defines classes that support atomic operations on single variables. All classes have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic </span><span style="font-size:11pt;">compareAndSet</span><span> method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables. </span></p>
<p class="MyBody"><span>To see how this package might be used, let&#8217;s return to the Counter class we originally used to demonstrate thread interference: </span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">class</span></strong> Counter {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">c</span> = 0;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> increment() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#0000c0;">c</span>++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> decrement() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <span style="color:#0000c0;">c</span>&#8211;;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">int</span></strong> value() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">            <strong><span style="color:#7f0055;">return</span></strong> <span style="color:#0000c0;">c</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">      }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span>One way to make Counter safe from thread interference is to make its methods synchronized, as in SynchronizedCounter: </span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">class</span></strong> SynchronizedCounter {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> <strong><span style="color:#7f0055;">int</span></strong> <span style="color:#0000c0;">c</span> = 0;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> increment() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">c</span>++;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">void</span></strong> decrement() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">c</span>&#8211;;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">synchronized</span></strong> <strong><span style="color:#7f0055;">int</span></strong> value() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> <span style="color:#0000c0;">c</span>;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">}</p>
<p class="MyBody"><span>For this simple class, synchronization is an acceptable solution. But for a more complicated class, we might want to avoid the liveness impact of unnecessary synchronization. Replacing the int field with an </span><span style="font-size:11pt;">AtomicInteger</span><span> allows us to prevent thread interference without resorting to synchronization, as in AtomicCounter: </span></p>
<p style="border:gray 1pt solid;padding:4pt 6pt;">
<p style="border:medium none;padding:0;" class="MyCodeCxSpFirst"><strong><span style="color:#7f0055;">import</span></strong> java.util.concurrent.atomic.AtomicInteger;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle"><strong><span style="color:#7f0055;">class</span></strong> AtomicCounter {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">private</span></strong> AtomicInteger <span style="color:#0000c0;">c</span> = <strong><span style="color:#7f0055;">new</span></strong> AtomicInteger(0);</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> increment() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">c</span>.incrementAndGet();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">void</span></strong> decrement() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <span style="color:#0000c0;">c</span>.decrementAndGet();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">&nbsp;</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    <strong><span style="color:#7f0055;">public</span></strong> <strong><span style="color:#7f0055;">int</span></strong> value() {</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">        <strong><span style="color:#7f0055;">return</span></strong> <span style="color:#0000c0;">c</span>.get();</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpMiddle">    }</p>
<p style="border:medium none;padding:0;" class="MyCodeCxSpLast">&nbsp;</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/shivpratap.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/shivpratap.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/shivpratap.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/shivpratap.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/shivpratap.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/shivpratap.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/shivpratap.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/shivpratap.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/shivpratap.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/shivpratap.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=shivpratap.wordpress.com&amp;blog=1141367&amp;post=11&amp;subd=shivpratap&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://shivpratap.wordpress.com/2007/10/17/multithreading-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/47f0954f3010c57d4d915afecaaa7595?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">shivpratap</media:title>
		</media:content>
	</item>
		<item>
		<title>Install SVN Client on Linux</title>
		<link>http://shivpratap.wordpress.com/2007/06/27/install-svn-client-on-linux/</link>
		<comments>http://shivpratap.wordpress.com/2007/06/27/install-svn-client-on-linux/#comments</comments>
		<pubDate>Wed, 27 Jun 2007 05:32:18 +0000</pubDate>
		<dc:creator>shiv pratap singh</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://shivpratap.wordpress.com/2007/06/27/install-svn-client-on-linux/</guid>
		<description><![CDATA[1. download neon 2. download apache-apr 3. download svn #1&#8211;&#62; install neon ./configure &#8211;with-ssl ./configure &#8211;with-neon=/usr/local/ #2&#8211;&#62; install apr-utils &#160; Step 1: Build and install apr 1.2 Go to the Source library directory of apr and follow the steps given below $ ./configure &#8211;prefix=/usr/local/apr-httpd/ $ make $ make install Step 2: Build and install apr-util [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=shivpratap.wordpress.com&amp;blog=1141367&amp;post=9&amp;subd=shivpratap&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p> 1. download neon</p>
<p>2. download apache-apr</p>
<p>3. download svn</p>
<p>#1&#8211;&gt; install neon</p>
<p>./configure &#8211;with-ssl</p>
<p>./configure &#8211;with-neon=/usr/local/</p>
<p>#2&#8211;&gt; install apr-utils</p>
<p class="MsoNormal">&nbsp;</p>
<p class="MsoNormal"><strong><span style="font-size:10pt;font-family:Arial;">Step 1</span></strong><span style="font-size:10pt;font-family:Arial;">: <span> </span>Build and install apr 1.2</span><span style="font-size:10pt;font-family:'Courier New';"><br />
</span><span style="font-size:10pt;font-family:Arial;">Go to the Source library directory of apr and follow the steps given below</span><span style="font-size:10pt;font-family:'Courier New';"></span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$ </span><span style="font-size:10pt;font-family:'Courier New';">./configure &#8211;prefix=/usr/local/apr-httpd/</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$ </span><span style="font-size:10pt;font-family:'Courier New';">make</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$ </span><span style="font-size:10pt;font-family:'Courier New';">make install</span><span style="font-size:10pt;font-family:'Courier New';"></span></p>
<p><strong><span style="font-size:10pt;font-family:Arial;">Step 2:</span></strong><strong><span style="font-size:10pt;font-family:'Courier New';"> </span></strong><strong><span style="font-size:10pt;font-family:'Courier New';"><span> </span></span></strong><span style="font-size:10pt;font-family:Arial;">Build and install apr-util 1.2</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$ </span><span style="font-size:10pt;font-family:'Courier New';">cd ../apr-util</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$ </span><span style="font-size:10pt;font-family:'Courier New';">./configure &#8211;prefix=/usr/local/apr-util-httpd/ &#8211;with-apr=/usr/local/apr-httpd/</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$</span><span style="font-size:10pt;font-family:'Courier New';">make</span></p>
<p class="MsoNormal"><span style="font-size:10pt;font-family:'Courier New';"><br />
$</span><span style="font-size:10pt;font-family:'Courier New';">make install</span></p>
<p>#3&#8212;&gt; install svn</p>
<h2><a title="_Toc168899622" name="_Toc168899622"></a><!--[if !supportLists]--><span style="font-size:12pt;font-style:normal;"><span><span style="font-family:'Times New Roman';font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;">              </span></span></span><!--[endif]--><span style="font-size:12pt;font-style:normal;">Pre-requisites</span><span style="font-size:12pt;font-style:normal;"></span></h2>
<p class="commenttext" style="margin-left:45pt;text-indent:-0.25in;"><!--[if !supportLists]--><span style="font-size:10pt;font-family:Symbol;"><span>·<span style="font-family:'Times New Roman';font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;">         </span></span></span><!--[endif]--><span style="font-size:10pt;font-family:Arial;">Src code are available and copied somewhere on disk</span></p>
<p class="commenttext" style="margin-left:45pt;text-indent:-0.25in;"><!--[if !supportLists]--><span style="font-size:10pt;font-family:Symbol;"><span>·<span style="font-family:'Times New Roman';font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;">         </span></span></span><!--[endif]--><span style="font-size:10pt;font-family:Arial;">Apr libraries required for svn are installed if not follow the guidelines in apache server installation to install apr.</span></p>
<p class="commenttext" style="margin-left:45pt;text-indent:-0.25in;"><!--[if !supportLists]--><span style="font-family:Symbol;"><span>·<span style="font-family:'Times New Roman';font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;">         </span></span></span><!--[endif]--><span style="font-size:10pt;font-family:Arial;">You need to be a superuser (root) to install and uninstall CollabNet</span> <span style="font-size:10pt;font-family:Arial;">SubversionInstallation</span></p>
<h2><a title="_Toc168899623" name="_Toc168899623"></a><!--[if !supportLists]--><span style="font-size:12pt;font-style:normal;"><span><span style="font-family:'Times New Roman';font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;">                </span></span></span><!--[endif]--><span style="font-size:12pt;font-style:normal;">Installation steps</span><span style="font-size:12pt;font-style:normal;"></span></h2>
<p class="commenttext"> <strong><span style="font-size:10pt;font-family:Arial;">Step 1:<span> </span>E</span></strong><span style="font-size:10pt;font-family:Arial;">xecute the command to install</span></p>
<p class="commenttext"><span style="font-size:10pt;font-family:Arial;">Extract the </span><span style="font-size:10pt;font-family:'Courier New';">tar.bz2 </span><span style="font-size:10pt;font-family:Arial;">file in one of the directory on your system</span></p>
<p class="commenttext"><span style="font-size:10pt;font-family:'Courier New';">$ bunzip &lt;filename&gt;.bz2</span></p>
<p class="commenttext"><span style="font-size:10pt;font-family:'Courier New';">$ tar –xvf &lt;filename&gt;.tar</span></p>
<pre></pre>
<pre><strong><span style="font-family:Arial;">Step 2:</span></strong> <span style="font-family:Arial;">Go to the directory where file is extracted</span> and e<span style="font-family:Arial;">xecute configure</span></pre>
<pre>$ ./configure –prefix=/opt/usnv/svn</pre>
<pre></pre>
<pre><strong><span style="font-family:Arial;">Step 3:</span></strong> <span style="font-family:Arial;">Execute make command</span></pre>
<pre>$make</pre>
<pre></pre>
<pre><strong><span style="font-family:Arial;">Step 4:</span></strong> <span style="font-family:Arial;">Execute make install command</span></pre>
<pre>$ make install</pre>
<pre></pre>
<pre><strong><span style="font-family:Arial;">Step 4:</span></strong> <span style="font-family:Arial;">Add the bin directory of svn installtion to your path</span></pre>
<pre>$ export PATH=${PATH}:/opt/usnv/svn/bin<strong><span style="font-family:Arial;">Step 5:</span></strong> <span style="font-family:Arial;">Test the installation by typing svn help command on prompt and press enter <span> </span>it should not show command not found but list of command available as shown below</span></pre>
<pre>$ svn help</pre>
<pre></pre>
<pre><span>usage: svn &lt;subcommand&gt; [options] [args]</span></pre>
<pre><span>Subversion command-line client, version 1.4.3.</span></pre>
<pre><span>Type 'svn help &lt;subcommand&gt;' for help on a specific subcommand.</span></pre>
<pre><span>Type 'svn --version' to see the program version and RA modules</span></pre>
<pre><span><span>  </span>or 'svn --version --quiet' to see just the version number.</span></pre>
<pre><span> </span></pre>
<pre><span>Most subcommands take file and/or directory arguments, recursing</span></pre>
<pre><span>on the directories.<span>  </span>If no arguments are supplied to such a</span></pre>
<pre><span>command, it recurses on the current directory (inclusive) by default.</span></pre>
<pre><span> </span></pre>
<pre><span>Available subcommands:</span></pre>
<pre><span><span>   </span>add</span></pre>
<pre><span><span>   </span>blame (praise, annotate, ann)</span></pre>
<pre><span><span>   </span>cat</span></pre>
<pre><span><span>   </span>checkout (co)</span></pre>
<pre><span><span>   </span>cleanup</span></pre>
<pre><span><span>   </span>commit (ci)</span></pre>
<pre><span><span>   </span>copy (cp)</span></pre>
<pre><span><span>   </span>delete (del, remove, rm)</span></pre>
<pre><span><span>   </span>diff (di)</span></pre>
<pre><span><span>   </span>export</span></pre>
<pre><span><span>   </span>help (?, h)</span></pre>
<pre><span><span>   </span>import</span></pre>
<pre><span><span>   </span>info</span></pre>
<pre><span><span>   </span>list (ls)</span></pre>
<pre><span><span>   </span>lock</span></pre>
<pre><span><span>   </span>log</span></pre>
<pre><span><span>   </span>merge</span></pre>
<pre><span><span>   </span>mkdir</span></pre>
<pre><span><span>   </span>move (mv, rename, ren)</span></pre>
<pre><span><span>   </span>propdel (pdel, pd)</span></pre>
<pre><span><span>   </span>propedit (pedit, pe)</span></pre>
<pre><span><span>   </span>propget (pget, pg)</span></pre>
<pre><span><span>   </span>proplist (plist, pl)</span></pre>
<pre><span><span>   </span>propset (pset, ps)</span></pre>
<pre><span><span>   </span>resolved</span></pre>
<pre><span><span>   </span>revert</span></pre>
<pre><span><span>   </span>status (stat, st)</span></pre>
<pre><span><span>   </span>switch (sw)</span></pre>
<pre><span><span>   </span>unlock</span></pre>
<pre><span><span>   </span>update (up)</span></pre>
<pre><span> </span></pre>
<pre><span>Subversion is a tool for version control.</span></pre>
<pre><span>For additional information, see <a href="http://subversion.tigris.org/">http://subversion.tigris.org/</a></span></pre>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/shivpratap.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/shivpratap.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/shivpratap.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/shivpratap.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/shivpratap.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/shivpratap.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/shivpratap.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/shivpratap.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/shivpratap.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/shivpratap.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=shivpratap.wordpress.com&amp;blog=1141367&amp;post=9&amp;subd=shivpratap&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://shivpratap.wordpress.com/2007/06/27/install-svn-client-on-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/47f0954f3010c57d4d915afecaaa7595?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">shivpratap</media:title>
		</media:content>
	</item>
	</channel>
</rss>
