<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>CertPal &#187; Java certifications</title>
	<atom:link href="http://www.certpal.com/blogs/category/java-cert/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.certpal.com/blogs</link>
	<description>Technology and certifications</description>
	<lastBuildDate>Mon, 18 Jul 2011 06:48:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Java thread tutorial</title>
		<link>http://www.certpal.com/blogs/2009/10/java-thread-tutorial/</link>
		<comments>http://www.certpal.com/blogs/2009/10/java-thread-tutorial/#comments</comments>
		<pubDate>Sun, 18 Oct 2009 10:51:00 +0000</pubDate>
		<dc:creator>CertPal</dc:creator>
				<category><![CDATA[Java certifications]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.certpal.com/blogs/?p=389</guid>
		<description><![CDATA[Java thread programming can be a little tricky to understand. This post provides a tutorial that SCJP candidates can use. The examples illustrate various scenarios that one encounters when using threads.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F10%2Fjava-thread-tutorial%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F10%2Fjava-thread-tutorial%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><img class="alignright size-full wp-image-393" title="j_thread_locks" src="http://www.certpal.com/blogs/wp-content/uploads/j_thread_locks.PNG" alt="j_thread_locks" width="140" height="115" />If you are a newbie to working with java threads, this post will help you. Certifications like the SCJP require you to understand java threads to a fair degree. Threads behavior can be difficult to understand even for experienced programmers, so I will try to present some examples which will help candidates identify how threads wait / lock and synchronize.</p>
<p>Lets cut the chit chat and jump into a problem. A program increments a counter in a for loop as shown below.</p>
<p><strong>Synchronizing:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticSync
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">Object</span> s_lock <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Object</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">int</span> s_counter<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> StaticSync<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">go</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> go<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> iCounter<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> iCounter<span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">50</span><span style="color: #339933;">;</span> iCounter<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Thread</span> thread <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Thread</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Incrementer<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> StaticSync<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            thread.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Incrementer <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Runnable</span>
<span style="color: #009900;">&#123;</span>
    StaticSync m_staticSync<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> Incrementer<span style="color: #009900;">&#40;</span>StaticSync staticSync_INP<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        m_staticSync <span style="color: #339933;">=</span> staticSync_INP<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #009900;">&#40;</span>m_staticSync.<span style="color: #006633;">s_lock</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            m_staticSync.<span style="color: #006633;">s_counter</span><span style="color: #339933;">++;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>m_staticSync.<span style="color: #006633;">s_counter</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This program is pretty simple. This is the sort of code that you can expect on the SCJP exam. Advanced versions of the code above can also appear by adding notify() wait() sleep() etc into the picture. Let us concentrate on the program for now. What can be guaranteed about the output of this program ?</p>
<p>Can we say that Numbers 1 through 50 will be printed for sure ? What can be said about the order in which they are printed. Is there a guarantee about that ?</p>
<p>This program prints numbers 1 through 50 and does it consistently. What that means is that we can guarantee that this program will print 1-&gt;50 in ascending order. Why ?</p>
<p><strong>Instances of a thread object lock on the same static object:</strong></p>
<p><img class="aligncenter size-full wp-image-394" title="j_thread_static_object_lock_1" src="http://www.certpal.com/blogs/wp-content/uploads/j_thread_static_object_lock_1.PNG" alt="j_thread_static_object_lock_1" width="294" height="310" /><strong></strong></p>
<p><strong>One thread manages to obtain a lock. The others wait:</strong></p>
<p><img class="aligncenter size-full wp-image-395" title="j_thread_static_object_lock_2" src="http://www.certpal.com/blogs/wp-content/uploads/j_thread_static_object_lock_2.PNG" alt="j_thread_static_object_lock_2" width="308" height="339" /></p>
<p>We are creating a new Incrementer instance while starting each thread. We are also passing it a new StaticSync instance for every thread. However when the code tries to update the counter, it synchronizes over a static object. The static object has only one instance, so when one of the 50 thread instances holds this lock, the other thread will have to wait until the lock is released.</p>
<p>Once the lock is released the next thread will update the counter variable. Since only one thread can obtain the lock at any given time, the operation of incrementing the counter and printing its value is atomic. What that means is that the ++ operation and the System.out.println() operation will happen without any other thread intefering in the middle. It happens as one single unit. Note that m_staticSync.s_lock is actually referring to the public static variable through a non static reference. This is not a recommended practice but it was used anyway to help readers understand the concept. The code also throws encapsulation out the window. Our focus is on the thread behavior of the code alone.</p>
<p>Now let us replace <strong>synchronized (m_staticSync.s_lock)</strong> with <strong>synchronized (this)</strong>. What do you think will change (if there is any) and why ? What does &#8220;this&#8221; refer to here and how is the locking different from the locking we did in the first example ? If the program is modified so that we synchronize over a static method, which Object&#8217;s lock do we obtain ?</p>
<p>I will leave these questions to you as an exercise. The images below should provide a hint.</p>
<p><strong>Threads locking on distinct object instances:</strong></p>
<p><img class="aligncenter size-full wp-image-399" title="j_thread_nonstatic_object_lock_1" src="http://www.certpal.com/blogs/wp-content/uploads/j_thread_nonstatic_object_lock_1.PNG" alt="j_thread_nonstatic_object_lock_1" width="227" height="324" /></p>
<p><strong>Everyone is a winner:</strong></p>
<p><img class="aligncenter size-full wp-image-400" title="j_thread_nonstatic_object_lock_2" src="http://www.certpal.com/blogs/wp-content/uploads/j_thread_nonstatic_object_lock_2.PNG" alt="j_thread_nonstatic_object_lock_2" width="223" height="322" /></p>
<p>Moving on to thread interruptions</p>
<p><strong>Interrupting:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ThreadInterrupt
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> ThreadInterrupt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">go</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> go<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span>
    <span style="color: #009900;">&#123;</span>
        InterruptTest interruptTest <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> InterruptTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">Thread</span> thread <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Thread</span><span style="color: #009900;">&#40;</span>interruptTest<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        thread.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">Thread</span>.<span style="color: #006633;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        thread.<span style="color: #006633;">interrupt</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">Thread</span>.<span style="color: #006633;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> InterruptTest <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Runnable</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">try</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Waiting&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                wait<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">30000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Inerrupted&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This class shows you how interruption of threads work. When a thread waits or sleeps, it goes into a blocking state. Such threads can be interrupted to come out of the blocking state. When such a thread gets &#8220;interrupted&#8221; from its blocking state, it throws an InterrutpedException. The output of the program above is</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Waiting
Inerrupted</pre></div></div>

<p>I have never used the interrupt() method at work. But it is useful to know that this can be done. Just remember that only threads that are blocking can be interrupted. Trying to interrupt threads in the running state will not work.</p>
<p><strong>Notification:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NotificationExample
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399;">Object</span> lock <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Object</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>... <span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> NotificationExample<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">go</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> go<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> iCounter<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> iCounter<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span><span style="color: #cc66cc;">100</span> <span style="color: #339933;">;</span> iCounter<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Thread</span> thread <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Thread</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ThreadWorker<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            thread.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">try</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">Thread</span>.<span style="color: #006633;">sleep</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #009900;">&#40;</span>lock<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            lock.<span style="color: #006633;">notifyAll</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> ThreadWorker <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Runnable</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #009900;">&#40;</span>NotificationExample.<span style="color: #006633;">lock</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">try</span>
            <span style="color: #009900;">&#123;</span>
                NotificationExample.<span style="color: #006633;">lock</span>.<span style="color: #006633;">wait</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Thread</span>.<span style="color: #006633;">currentThread</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; finished waiting&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The SCJP exam expects you to understand how waiting and notifications happen in Threads. In this example, several threads synchronize over the same lock and then wait. A few seconds later a notifyAll() call is made to notify all the threads that were waiting on this Object&#8217;s lock. As an exercise, try to change the notifyAll() call to notify(). Observe what change that does to the execution of this program.</p>
<p>Some of the code displayed above uses the sleep() method to better explain and understand Thread behaviour when you run the examples. However making a Thread sleep does not guarantee any given result. You need to keep that in mind. The scenarios may also play out differently when you remove the calls to sleep(). What would happen for example if the notify() method is called before the threads actually begin waiting ?</p>
<p>You can toy around with those three examples to get a better grasp on threads.
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F10%2Fjava-thread-tutorial%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F10%2Fjava-thread-tutorial%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.certpal.com/blogs/2009/10/java-thread-tutorial/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java &#8211; Console</title>
		<link>http://www.certpal.com/blogs/2009/08/java-console/</link>
		<comments>http://www.certpal.com/blogs/2009/08/java-console/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 11:14:07 +0000</pubDate>
		<dc:creator>CertPal</dc:creator>
				<category><![CDATA[Java certifications]]></category>
		<category><![CDATA[console]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[scjp]]></category>

		<guid isPermaLink="false">http://www.certpal.com/blogs/?p=8</guid>
		<description><![CDATA[Sun introduced the java.io.console class to enable developers to obtain passwords / other sensitive data from the console / terminal. This article delves into the class a little.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-console%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-console%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>To get sensitive user input without echoing it to the 						console/terminal, the Java SDK has introduced the <strong> java.io.Console class.</strong> The Console class is quite unique 						in the way it handles its data. It uses the native encoding of the 						system instead of the using the JVM&#8217;s default encoding.</p>
<p>The Console class provides methods to access the console/terminal, if any is 							associated with the JVM.</p>
<p><strong>Using the Console class:</strong><br />
So how do you use the Console class ? Its pretty simple really. 						First get a reference to the Console class from the System class</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Console con <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">console</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It is not always possible to get a reference to the console. Some 						scenarios prevent the developer from gaining access to the 						console. This method may return null in these cases. For example a batch 							process running on a server will not expect user input and 							usually does have a console. Your code must be capable of handling such situations.</p>
<p>Consider that you have a program that requires the user to secretly type in his/her password.</p>
<p><strong> Entering sensitive data through the console:</strong><br />
<strong> </strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Console con <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">console</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> user <span style="color: #339933;">=</span> con.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Username: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> password <span style="color: #339933;">=</span> con.<span style="color: #006633;">readPassword</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Password: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you were to run this code using the eclipse IDE it would not 						work (At least in eclipse 3.2).<br />
This is because eclipse does not handle this code properly as 							yet. Run this code from the command prompt for 							now. Here is the output of the program</p>
<p><strong> Output:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">java com.<span style="color: #006633;">Tests</span>.<span style="color: #006633;">Cert</span>
Username<span style="color: #339933;">:</span> hello
Password<span style="color: #339933;">:</span></pre></div></div>

<p>Even though the output does not show a password being typed in, 						the user has typed it in on the console. The console&#8217;s 						feature allows the user to type in the password without it being 						echoed to the screen.</p>
<p>The line of code con.readLine(&#8220;Username: &#8220;); reads data from the 							console normally and stores it into a string. It also 							echoes whatever the user types onto the screen (you can see 							&#8220;hello&#8221; on the output). The line of code 							con.readPassword(&#8220;Password: &#8220;); prompts the user for a password 							but does not echo the contents of the password to the screen. 							This allows the user to enter his/her password safely using the 							Console class. To format the output to the screen the following 							code can be used.</p>
<p><strong> Formatting data:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Console con <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">console</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> user <span style="color: #339933;">=</span> con.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Welcome %s. Please login <span style="color: #000099; font-weight: bold;">\n</span>Username:&quot;</span>,<span style="color: #0000ff;">&quot;Guest&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> password <span style="color: #339933;">=</span> con.<span style="color: #006633;">readPassword</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;What is your password %s:&quot;</span>,user<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;User: &quot;</span> <span style="color: #339933;">+</span> user <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Password: &quot;</span> <span style="color: #339933;">+</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span> <span style="color: #009900;">&#40;</span>password<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Output</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">java com.<span style="color: #006633;">Tests</span>.<span style="color: #006633;">Cert</span>
Welcome Guest. <span style="color: #006633;">Please</span> login
Username<span style="color: #339933;">:</span> hello
What is your password hello<span style="color: #339933;">:</span>
User<span style="color: #339933;">:</span> hello
Password<span style="color: #339933;">:</span> bla</pre></div></div>

<p>Notice that although the password is not visible in the console 						screen, the program was able to retrieve it. Also the line of code 						con.readPassword(&#8220;What is your password %s: &#8220;,user); will format 						the output such that the username is present when asking for the 						password. %s represents the String that was passed to the method.                          Now let&#8217;s take a look at using the format() method.</p>
<p><strong>Formatting output only: </strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Console con <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">console</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
con.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Welcome %s <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, <span style="color: #0000ff;">&quot;Mr bond&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> user <span style="color: #339933;">=</span> con.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Username: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> password <span style="color: #339933;">=</span> con.<span style="color: #006633;">readPassword</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;What is your password %s:&quot;</span>,user<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;User: &quot;</span> <span style="color: #339933;">+</span> user <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Password: &quot;</span> <span style="color: #339933;">+</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span> <span style="color: #009900;">&#40;</span>password<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong> Output:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Welcome Mr bond
Username<span style="color: #339933;">:</span> 007
What is your password 007<span style="color: #339933;">:</span>
User<span style="color: #339933;">:</span> 007
Password<span style="color: #339933;">:</span> goldeneye</pre></div></div>

<p>In this case the formatting that was present in the readLine() 						method has been transferred to the format() method. Console also 						has a printf() method that works similar to the format() method. 						This method however has been made available only for convenience. 						Finally you can make use of the reader and writer classes to read 						and write to the Console.</p>
<p><strong> Reader and Writer: </strong><br />
Note: This code throws IOException since we need read/write access to the console</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">char</span> buffer<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1024</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
Console con <span style="color: #339933;">=</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">console</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">Reader</span> reader <span style="color: #339933;">=</span> con.<span style="color: #006633;">reader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">int</span> numRead <span style="color: #339933;">=</span> reader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// #1</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span> <span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, numRead<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">Writer</span> writer <span style="color: #339933;">=</span> con.<span style="color: #006633;">writer</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// #2</span>
writer.<span style="color: #006633;">write</span><span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
writer.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
writer.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong> Output:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">reader <span style="color: #339933;">--</span> #a. <span style="color: #006633;">Input</span> provided by a user
reader <span style="color: #339933;">--</span> #b. <span style="color: #006633;">Written</span> by <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>
reader <span style="color: #339933;">--</span> #c. <span style="color: #006633;">Written</span> by console writer</pre></div></div>

<p>The #a reader is the input that was provided to the program. The 						program reads this data using the Reader class. It reads the data 						into a character buffer in line #1 and prints the data to the console 						. At line #2 the console&#8217;s writer is obtained by the program 						and the contents of the character buffer are sent to the console 						output again (this time using System.out). Be wary however, when you 						use the Reader and Writer classes. They throw the IOException and 						since this is a checked Exception it must be handled. The 						code above throws this exception from a method (not shown) and thus need not 						handle it.</p>
<p><a href="../../index.html">Back to home</a>
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-console%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-console%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.certpal.com/blogs/2009/08/java-console/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Sun java certification pitfalls</title>
		<link>http://www.certpal.com/blogs/2009/08/sun-java-exam-pitfalls/</link>
		<comments>http://www.certpal.com/blogs/2009/08/sun-java-exam-pitfalls/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 10:46:32 +0000</pubDate>
		<dc:creator>CertPal</dc:creator>
				<category><![CDATA[Java certifications]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[drag and drop]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pitfall]]></category>
		<category><![CDATA[review]]></category>

		<guid isPermaLink="false">http://www.certpal.com/blogs/?p=39</guid>
		<description><![CDATA[Before you can go ahead and take the real Sun Java exams, you need to know some of the pitfalls that have plagued several test takers. Here are a few pointer Do not buy a voucher before you are prepared to take the exam: Often some candidates like to follow this approach hoping that the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fsun-java-exam-pitfalls%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fsun-java-exam-pitfalls%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Before you can go ahead and take the real Sun Java exams, you need to know some of the pitfalls that have plagued several test takers. Here are a few pointer</p>
<p><strong> Do not buy a voucher before you are prepared to take the exam: </strong></p>
<p>Often some candidates like to follow this approach hoping that the purchase of the voucher would force them to learn within a given time period. On the contrary this adds additional pressure to your preparation, since you need to study the objectives before the expiry date. Some candidates have lost money misinterpreting the expiry date on the voucher. Be wary of the <strong> MM/DD/YYYY Vs DD/MM/YYYY </strong> formats. Which one does your voucher display ?</p>
<p>When the candidates finally find that they have no more time to learn, they post a message on a forum that reads something like &#8216;I have voucher for exam X for a discount of Y%. Please call me to buy&#8217;. Remember, you are a candidate, not a voucher reseller <img src='http://www.certpal.com/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong> Material made available to you inside the exam room: </strong></p>
<p>Prometric centers will not provide you with pen/paper/pencil at the time of the exam. You will be given a plastic sheet and a marker/felt pen. You can jot down on the plastic sheet with the pen.</p>
<p>Mobile phones, PDAs, and other object that would allow a candidate to cheat are not allowed. Also make sure that once you are ready, you book your exam slot in advance. This ensures that you dont spend anxious minutes waiting to buy one just before the exam.</p>
<p><strong> Beware of drag and drops: </strong></p>
<p>All Sun Java certification real exams run on a managed software. This software has a user interface where some questions require that you drag elements and drop them into their appropriate places. Beware though, once you answer a drag and drop question you <strong>cannot review</strong> its answer again. Which means if you do answer the Drag and drop question, when you try to review the answer next time the answer will be lost / reset. If you want to, you can jot down the drag and drop answer on the plastic sheet given to you and review it later.</p>
<p><strong> Code analysis: </strong></p>
<p>It is important to analyze the code presented to you even before you attempt to find the solution. Scan the entire class for well known problems before continuing your analysis</p>
<ul>
<li>Are non-static variables referred from a static context ?</li>
<li>Are there infinite loops ?</li>
<li>Is there a compile time error ?</li>
<li>Are method overridden correctly ?</li>
<li>etc etc&#8230;</li>
</ul>
<p>Once you know how to scan for such patterns, answering the question will become easier.</p>
<p><strong> Am I ready ?: </strong></p>
<p>So when do you that you are ready to take the exam ? Thats a tough one to answer. There are candidates that get 50% on the mock exam but pass the real exam with flying colors. Then there are the ones that pass mock exams and fail the real one. The latter group is rare. At the end of the day if you know what your weak points are and you are confident that you can strengthen them, go for it !.</p>
<p><a href="../../index.html">Back to home</a>
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fsun-java-exam-pitfalls%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fsun-java-exam-pitfalls%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.certpal.com/blogs/2009/08/sun-java-exam-pitfalls/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java &#8211; Navigable Set</title>
		<link>http://www.certpal.com/blogs/2009/08/java-navigable-set/</link>
		<comments>http://www.certpal.com/blogs/2009/08/java-navigable-set/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 13:42:26 +0000</pubDate>
		<dc:creator>CertPal</dc:creator>
				<category><![CDATA[Java certifications]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[navigableset]]></category>
		<category><![CDATA[scjp]]></category>

		<guid isPermaLink="false">http://www.certpal.com/blogs/?p=16</guid>
		<description><![CDATA[Sun introduced the NavigableMap class in JDK 6. This article details how to work with this class by providing a short tutorial.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-navigable-set%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-navigable-set%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><strong>Sets:</strong></p>
<p>A Set is a collection that contains no duplicate elements. Sets are collections where no two elements are the same, which means that element1.equals(element2) should never return true. Also at most one element in a set can be null and no more.</p>
<p><strong>A Set. Duplicates are not allowed and at most one null element is allowed</strong></p>
<p style="text-align: center"><strong><img class="aligncenter" src="http://www.certpal.com/images/set.JPG" alt="" width="138" height="269" /></strong></p>
<p><strong>Sorted Sets:</strong></p>
<p>A <strong>SortedSet </strong>is a set which sorts and maintains the ordering of its elements. Elements will be ordered by their natural ordering or by the use of a Comparator (if the developer provides one). A <a href="http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html">Comparable</a> interface can help define the ordering for elements. For example a String’s natural ordering will dictate that elements be ordered this way “a”, “b”, “c” etc. The way in which elements are ordered in a Sorted data structure can be redefined by using the <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html">Comparator</a> interface.</p>
<p><strong> Sorted set where elements are sorted by natural order.</strong></p>
<p><strong><img class="aligncenter" src="http://www.certpal.com/images/sorted_set.JPG" alt="" width="86" height="258" /></strong></p>
<p><strong>Navigable set:</strong></p>
<p>A navigable set is a sorted set. Technically this means that a NavigableSet extends from a SortedSet. The navigable set has a couple of methods that will return the closest matching element given a search target. A NavigableSet can be accessed in the ascending or descending order. To get an ascending view of this structure the iterator() method can be used like in all Collection classes. To get a descending view of this structure use the descendingIterator() method. This method returns an Iterator whose elements are in the reverse natural order. That.s a fancy way of saying .in descending order. <img src='http://www.certpal.com/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The implementations of NavigableSet are the TreeSet and the ConcurrentSkipListSet. Let us take an example of the Iteration orders of the navigable set</p>
<p><strong>Code: </strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> 
<span style="color: #009900;">&#123;</span>
    NavigableSet <span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> navigableSet  <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TreeSet<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    navigableSet.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    navigableSet.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">20</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    navigableSet.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    navigableSet.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">40</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    navigableSet.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">90</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Iterator<span style="color: #339933;">&lt;</span> Integer<span style="color: #339933;">&gt;</span> iterator <span style="color: #339933;">=</span> navigableSet.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Iterator<span style="color: #339933;">&lt;</span> Integer<span style="color: #339933;">&gt;</span> reverseIterator <span style="color: #339933;">=</span> navigableSet.<span style="color: #006633;">descendingIterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Forward ahoy !&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Reverse yoha !&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>reverseIterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>reverseIterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>Output:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">The output of <span style="color: #000000; font-weight: bold;">this</span> program would be<span style="color: #339933;">:</span>
Forward ahoy <span style="color: #339933;">!</span>
<span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>
<span style="color: #cc66cc;">10</span>
<span style="color: #cc66cc;">20</span>
<span style="color: #cc66cc;">40</span>
<span style="color: #cc66cc;">90</span>
&nbsp;
Reverse yoha <span style="color: #339933;">!</span>
<span style="color: #cc66cc;">90</span>
<span style="color: #cc66cc;">40</span>
<span style="color: #cc66cc;">20</span>
<span style="color: #cc66cc;">10</span>
<span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span></pre></div></div>

<p>As expected the Iterators iterate through the set in the natural and reverse natural order. Tree sets also automatically sort their elements. There are some key methods that make the NavigableSet useful in certain scenarios. We will have a look at them now.</p>
<p><strong>Key methods in the NavigableSet:</strong></p>
<p>Don&#8217;t worry if some of these methods do not make sense. We will take a look at them with an example</p>
<table style="height: 215px;" border="1" cellspacing="1" cellpadding="1" width="500" align="center">
<tbody>
<tr>
<td align="center"><strong> Method name</strong></td>
<td align="center"><strong> What element will It return ?</strong></td>
</tr>
<tr>
<td align="center">lower(element)</td>
<td align="center">Less than current element</td>
</tr>
<tr>
<td align="center">floor(element)</td>
<td align="center">Less than or equal to current element</td>
</tr>
<tr>
<td align="center">ceiling(element)</td>
<td align="center">Greater than or equal to current element</td>
</tr>
<tr>
<td align="center">higher(element)</td>
<td align="center">Greater than current element</td>
</tr>
<tr>
<td align="center">subSet(fromElem,isInclusive ,toElem, isInclusive)</td>
<td align="center">Returns a subset of the Set from an element to another. Flags can be set to mention if the elements should be inclusive or not</td>
</tr>
<tr>
<td align="center">headSet(toElem,isInclusive)</td>
<td align="center">A subset of this set whose elements are strictly less than toElem</td>
</tr>
<tr>
<td align="center">tailSet(fromElem,isInclusive)</td>
<td align="center">A subset of this set whose elements are greater than toElem</td>
</tr>
<tr>
<td align="center">descendingSet()</td>
<td align="center">Returns a set whose elements are in the descending order</td>
</tr>
<tr>
<td align="center">pollFirst()</td>
<td align="center">Retrieve and remove the first element</td>
</tr>
<tr>
<td align="center">pollLast()</td>
<td align="center">Retrieve and remove the last element</td>
</tr>
</tbody>
</table>
<p>A small program illustrates each method. Assume that a NavigableSet is inserted with the following data just like before.</p>
<p><strong> Values added into the set in this order:</strong></p>
<p><img class="alignnone" src="http://www.certpal.com/images/set_order.JPG" alt="" width="379" height="59" /></p>
<p>Let&#8217;s say the following lines were executed in the program</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">floor</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">ceiling</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">lower</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">higher</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">higher</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">90</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>The output would be as follows:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>
<span style="color: #cc66cc;">10</span>
<span style="color: #cc66cc;">20</span>
<span style="color: #cc66cc;">40</span>
<span style="color: #000066; font-weight: bold;">Null</span></pre></div></div>

<p>To explain the output, let&#8217;s arrange the elements first, the way a sorted set would see them</p>
<p><img class="alignnone" src="http://www.certpal.com/images/set_arrange.JPG" alt="" width="391" height="57" /></p>
<p>When the Set encounters methods like floor(),ceiling() etc, this is what it translates to.</p>
<p><strong>floor(5) </strong>– Give me the element that is less than or equal to 5. Result is -10</p>
<p><strong>ceiling(5) </strong>- Give me the element that is greater than or equal to 5. Result is 10</p>
<p><strong>lower(30) </strong>- Give me the element that is less than 30. Result is 20</p>
<p><strong>higher(30) </strong>- Give me the element that is greater than 30. Result is 40</p>
<p>Any request for an element that does not match the criteria will result in a <strong>null </strong>return. For example a request to the set to return something higher than 90 gives null since 90 is the highest value in the set.</p>
<p><strong> More examples:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">subSet</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span>,<span style="color: #000066; font-weight: bold;">true</span>,<span style="color: #cc66cc;">40</span>,<span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">tailSet</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>, <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">headSet</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">40</span>, <span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">descendingSet</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>The output:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">40</span><span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">40</span>, <span style="color: #cc66cc;">90</span><span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#91;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">40</span><span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">90</span>, <span style="color: #cc66cc;">40</span>, <span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">10</span>, <span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#93;</span></pre></div></div>

<p>Again, given the sorted set this result can be explained.</p>
<p><img class="alignnone" src="http://www.certpal.com/images/sorted_set_2.JPG" alt="" width="393" height="57" /></p>
<p><strong>subSet(10,true,40,true)</strong>- Give me all the elements between 10 and 40, inclusive of 10 and 40.</p>
<p><strong>tailSet(-10, false) </strong>- Give me all the elements after -10, exclusive of -10.</p>
<p><strong>headSet(40, true)</strong>- Give me all the elements before 40, inclusive of 40.</p>
<p><strong>descendingSet()</strong>- Show me the Navigable set in descending order</p>
<p>The descending set is nothing but the set in reverse order. It is helpful if you need the entire set in descending order instead of a descending Iterator to the set. That laves us with pollFirst() and pollLast().</p>
<p><strong>Polling through navigable sets:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">pollFirst</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet.<span style="color: #006633;">pollLast</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>navigableSet<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Output</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #009900;">&#91;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">40</span>, <span style="color: #cc66cc;">90</span><span style="color: #009900;">&#93;</span>
<span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>
<span style="color: #cc66cc;">90</span>
<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">40</span><span style="color: #009900;">&#93;</span></pre></div></div>

<p>The pollFirst() method retrieves and removes the first value in the set. Which is -10. The pollLast() method retrieves and removes the last value in the set, which is 90. As a result the set.s final size is reduced by 2. After removal of -10 and 90 from the set, the final set looks like this [10, 20, 40].</p>
<p>The <a href="http://java.sun.com/javase/6/docs/api/java/util/NavigableMap.html">NavigableMap</a> API is very similar to that of the NavigableSet (It is unfair to compare a Map and Set, but you get the picture). Now that you know how to use a NavigableSet, learning the NavigableMap should easy.</p>
<p><a href="../../index.html">Back to home</a>
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-navigable-set%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.certpal.com%2Fblogs%2F2009%2F08%2Fjava-navigable-set%2F&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.certpal.com/blogs/2009/08/java-navigable-set/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>

