Friday 13 January 2012

How to write build.xml and run build in Apache ANT

This is the second article on Apache ANT tutorials for beginners series As I have always said that I like short , clear and concise tutorial which tells about few concept but in a clear and concise manner and put weight on fundamentals . I try to adopt same theory while writing my blog post while writing my experience coupled with concept which is important for a software developer point of view.


Here I am answering some of the basic questions related to installing ant , running ant , creating buidl.xml file , debugging build.xml in case of any issue .

These questions have been asked by my students , while teaching them JAVA and related technology  in my early career.

How do I run ant?
To run you need to download ant and install on your machine , then create environment variable ANT_HOME and include ANT_HOME/bin into your PATH like below.

In Windows path=%path%;%ANT_HOME%/bin
In Linux    PATH =${PATH}:${ANT_Home}/bin

Now you can open command prompt and type ant.

If you get this output, means ant binaries is not in your path

C:\Documents and Settings>ant
'ant' is not recognized as an internal or external command,operable program or batch file.

Otherwise you will get output which will complain about build file if it doesn’t exits.
   
    C:\Documents and Settings>ant
    Buildfile: build.xml does not exist!
    Build failed

How do I write build.xml file?
here is a sample build.xml you just need to know important element e.g. project ,target ,property and task and the order in which different target gets executed to start with basic build procedure.

<?xml version="1.0"?>
<project name="test" default="all" basedir=".">
  <property name="src"   value="src"/>
  <property name="build" value="build"/>
  <property name="lib"   value="lib"/>

<target name="all" depends="clean, compile" description="Builds the whole project">
    <echo>Doing all</echo>
  </target>

<target name="Clean" description="Removes previous build">
    <delete verbose="true">
      <fileset dir="${build}"/>
    </delete>
  </target>

<target name="compile" depends="clean" description="compile whole project">
    <echo>compile ${ant.project.name} </echo>
    <copy file="${src}/splashscreen.jpeg" tofile="${build}/splashscreen.jpeg"/>
    <javac srcdir="${src}" destdir="${build}" includes="Test.java"/>
  </target>
</project>

lets see what we are doing here :

<project name="test" default="all" basedir=".">

This line defines our project; every build file must have this line. Project name is “test” defined by attribute “name”; default target is “all”, while running “ant” command from commmand prompt if we don’t specify any target than ant executed this default target.
basedir tells which is top level directory for creating build in this case its current directory (from where you run ant command) , denoted by dot “.” .

<property name="src"   value="src"/>

Here we are declaring and specifying property ,you can say variable every property has atleast two attribute “name” and “value” , though you can define your all properties in a separate properties file and load from there as well .<property> denotes ant’s property task, which do have some other attribute e.g. location to specify location of any properties file. I recommend that you always use property in your build.xml instead of using hardcoded values in target for directory name etc , this will give you flexibility to change the value anytime without changing at many places (in case you have hardcoded it).

<target name="all" depends="clean, compile" description="Builds the whole project">
Here we are defining a target, since we have already called target “all” as default in project tag, so if we don’t specify this target our build will fail saying “target not found”.

”name” attribute specified name of target. “depends” says that before executing this target executed first “clean” and then “compile”

<echo>Doing all</echo>
This will print message in console as “doing all”


<target name="Clean" description="Removes previous build">
This is target “Clean” which will delete old build before building new one , you can have as many target as you want based on your need.

<delete verbose="true">
      <fileset dir="${build}"/>
</delete>

delete task or tag is used to delete directory, file etc, verbose=true makes it to print message while deleting in cosole, <fileset> is an important tag and I recommend you to read in detail somewhere in ant manual or may be I will explain in detail sometime because it include “patternset” which supports pattern matching of directory/files via its includes and excludes attribute which is extremely useful to filter unwanted files (generally meta data files form CVS, SVN etc).

Here we are deleting build directory by using value of property “build”, ${build} denotes value of any property.

<target name="compile" depends="clean" description="compile whole project">
    <echo>compile ${ant.project.name} </echo>
    <copy file="${src}/splashscreen.jpeg" tofile="${build}/splashscreen.jpeg"/>
    <javac srcdir="${src}" destdir="${build}" includes="Test.java"/>
  </target>
</project>

This is our compile target ,which compiles our code and also copies resources e.g. images, we can also create jar file using ant, which we are not doing here just for simplicity.

Imporant thing here is property ${ant.project.name} this is builtin propety provided by ant and its’s value is name of project defined by attribute “name” of proejct tag.

<copy> tag is used to copy files and <javac> tag is used to compile java code .

How do I debug build.xml?
if you see problem on your build or you are getting exception related to findiing files/directory or anything then you would like to know what’s going behind there are two option , run ant on verbose option , it will print lots of detail (I don’t prefer this) because of so much unwanted information but can be usefule in certain situation.

Second and my preffered way is good old “echo” way . use echo task to print values of properties, variables or printing simple message to check the work flow.

here are some example of using echo

<echo>Doing all</echo>
<echo message="Now creating directory source "/>
<echo level="warning" message ="Active configuration (config.active property) is not set - using default." />


How do I enforce ant to use file other than build.xml?
Normally when you run ant from any directory from command prompt it will look for file called build.xml in current directory; if it doesn’t find the file it will give error. If you have file named “custom_build.xml” you can instruct ant to use this file for building your application by using option “-f” e.g. ant –f custom_build.xml

Hope this would be useful let me know if you have any questions, doubt etc will be happy to answer.

How to traverse or loop HashMap in Java Example

There are multiple way to iterate, traverse or loop through Map, HashMap or TreeMap in Java and we all familiar of either all of those or some of those. But to my surprise one of my friends was asked in his interview (he has more than 6 years of experience in java programming) to write code for getting values from hashmap or TreeMap in Java with at least 4 ways. Just like me he also surprised on this question but written it. I don't know why exactly some one ask this kind of java interview question to a relatively senior java programmer. Though my closest guess is to verify that whether he is still hands on with coding in java. Anyway that gives me idea to write this Java tutorial and here is multiple ways to traverse, iterate or loop on a Map in Java, so remember this because you may also ask this question J.

How to traverse or loop Map, HashMap or TreeMap in Java

In next section of this Java tutorial we will see four different ways of looping or iterating over Map in Java and will display each key and value from HashMap. We will use following hashmap for our example:

HashMap<String, String> loans = new HashMap<String, String>();
loans.put<"home loan", "citibank");
loans.put<"personal loan", "Wells Fargo");


Iterating or looping map using Java5 foreach loop
Here we will use new foreach loop introduced in JDK5 for iterating over any map in java and using KeySet of map for getting keys. this will iterate through all values of Map and display key and value together.

HashMap<String, String> loans = new HashMap<String, String>();
loans.put("home loan", "citibank");
loans.put("personal loan", "Wells Fargo");

for (String key : loans.keySet()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating or looping map using java5 foreach loop");
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: home loan value: citibank
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: personal loan value: Wells Fargo



Iterating Map in Java using KeySet Iterator
In this Example of looping hashmap in Java we have used Java Iterator instead of for loop, rest are similar to earlier example of looping:

Set<String> keySet = loans.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating Map in Java using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating Map in Java using KeySet Iterator
key: home loan value: citibank
------------------------------------------------
Iterating Map in Java using KeySet Iterator
key: personal loan value: Wells Fargo


Looping HashMap in Java using EntrySet and Java5 for loop
In this Example of traversing Map in Java, we have used EntrySet instead of KeySet. EntrySet is a collection of all Map Entries and contains both Key and Value.

Set<Map.Entry<String, String>> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("------------------------------------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: home loan value: citibank
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: personal loan value: Wells Fargo


Iterating HashMap in Java using EntrySet and Java iterator
This is the fourth and last example of looping Map and here we have used Combination of Iterator and EntrySet to display all keys and values of a Java Map.

Set<Map.Entry<String, String>> entrySet1 = loans.entrySet();
Iterator<Entry<String, String>> entrySetIterator = entrySet1.iterator();
while (entrySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating HashMap in Java using EntrySet and Java iterator");
   Entry entry = entrySetIterator.next();
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
Iterating HashMap in Java using EntrySet and Java iterator
key: home loan value: citibank
------------------------------------------------
Iterating HashMap in Java using EntrySet and Java iterator
key: personal loan value: Wells Fargo


That’s all on multiple ways of looping Map in Java. We have seen exactly 4 examples to iterator on Java Map in combination of KeySet and EntrySet by using for loop and Iterator. Let me know if you are familiar with any other ways of iterating and getting each key value from Map in Java.

How to Convert Map to List in Java Example

Map and List are two common data-structures available in Java and in this article we will see how can we convert Map values or Map keys into List in Java. Primary difference between Map (HashMap, ConcurrentHashMap or TreeMap) and List is that Map holds two object key and value while List just holds one object which itself is a value. Key in hashmap is just an addon to find values, so you can just pick the values from Map and create a List out of it. Map in Java allows duplicate value which is fine with List which also allows duplicates but Map doesn't allow duplicate key.


How to Convert Map into List in Java with Example

Map to List Example in Java
Here are few examples of converting Map to List in Java. We will see first how to convert hashMap keys into ArrayList and than hashMap values into ArrayList in Java.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 *Converting HashMap into ArrayList in Java
 */
public class MaptoListJava {

    public static void main(String... args) {
        HashMap<String, String> personalLoanOffers = new HashMap<String, String>();
        // preparing hashmap with keys and values
        personalLoanOffers.put("personal loan by DBS", "Interest rate low");
        personalLoanOffers.put("personal loan by Standard Charted", "Interest rate low");
        personalLoanOffers.put("HSBC personal loan by DBS", "14%");
        personalLoanOffers.put("Bankd of America Personal loan", "11%");
     
        System.out.println("Size of personalLoanOffers Map: " + personalLoanOffers.size());
     
        //Converting HashMap keys into ArrayList
        List<String> keyList = new ArrayList<String>(personalLoanOffers.keySet());
        System.out.println("Size of Key list from Map: " + keyList.size());
     
        //Converting HashMap Values into ArrayList
        List<String> valueList = new ArrayList<String>(personalLoanOffers.values());
        System.out.println("Size of Value list from Map: " + valueList.size());


     
        List<Entry> entryList = new ArrayList<Entry>(personalLoanOffers.entrySet());
        System.out.println("Size of Entry list from Map: " + entryList.size());

    }
}

Output:
Size of personalLoanOffers Map: 4
Size of Key list from Map: 4
Size of Value list from Map: 4
Size of Entry list from Map: 4

That's all on Map to List Conversion in Java , as you seen in above example you can create separate list for both keySet and values Collection in Java. let me know if you know any other way except brute force way of going through each element of Map and copying into List.

How to read and write Images in java using ImageIO Utility

Writing an Image file in Java is very common scenario and in this article we will see a new way to write images into file in Java. javax.imageio.ImageIO is a utility class which provides lots of utility method related to images processing in Java. Most common of them is reading form image file and writing images to file in java. You can write any of .jpg, .png, .bmp or .gif images to file in Java. Just like writing, reading is also seamless with ImageIO and you can read BufferedImage directly from URL. Reading Images are little different than reading text or binary file in Java as they they are associated with different format. Though you can still use getClass().getResourceAsStream() approach for loading images.


Image Read Write Example using ImageIO

Code Example Image Read and Write in Java
Here is complete Code Example of reading and writing Images to file in Java, we will first read the image and than write the same image in different format e.g. JPG, PNG and BMP into disk.

In this code Exmaple of javax.imageio.ImageIO class we will see:

How to read Buffered Image in Java from File or URL
How to write JPG images to file in Java
How to write PNG images to file in Java
How to write BMP images to file in Java
How to write GIF images to file in Java



import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;



public class ImageIOExample {   

    public static void main( String[] args ){
       BufferedImage image = null;
        try {

              //you can either use URL or File for reading image using ImageIO
            File imagefile = new File("C://Documents and Settings/Javin/My Documents/My Pictures/loan.PNG");
            image = ImageIO.read(imagefile);

            //ImageIO Image write Example in Java
            ImageIO.write(image, "jpg",new File("C:\\home_loan.jpg"));
            ImageIO.write(image, "bmp",new File("C:\\credit_card_loan.bmp"));
            ImageIO.write(image, "gif",new File("C:\\personal_loan.gif"));
            ImageIO.write(image, "png",new File("C:\\auto_loan.png"));

        } catch (IOException e) {
              e.printStackTrace();
        }
        System.out.println("Success");
    }
}

Apart from seemless support of reading and writing images in Java, ImageIO class also contains lot of other utility methods for locating ImageReaders and ImageWriters and performing encoding and decoding.

That's all on this Reading and Writing Image File in Java using javax.imageio.ImageIO. Let me know if you face any issue while trying these examples of ImageIO.

Difference between DOM and SAX Parsers in Java

Difference between SAX and DOM Parser is very popular Java interview and often asked when interviewed on Java and XML. Both DOM and SAX parser are extensively used to read and parse XML file in java and have there own set of advantage and disadvantage which we will cover in this article. Though there is another way of reading xml file using xpath in Java which is more selective approach like SQL statements people tend to stick with XML parsers. DOM Parser vs SAX parsers are also often viewed in terms of speed, memory consumption and there ability to process large xml files.


Difference between DOM and SAX XML Parser in Java

DOM XML Parser in Java

DOM Stands for Document Object Model and it represent an XML Document into tree format which each element representing tree branches. DOM Parser creates an In Memory tree representation of XML file and then parses it, so it requires more memory and its advisable to have increased heap size for DOM parser in order to avoid Java.lang.OutOfMemoryError:java heap space . Parsing XML file using DOM parser is quite fast if XML file is small but if you try to read a large XML file using DOM parser there is more chances that it will take a long time or even may not be able to load it completely simply because it requires lot of memory to create XML Dom Tree. Java provides support DOM Parsing and you can parse XML files in Java using DOM parser. DOM classes are in w3c.dom package while DOM Parser for Java is in JAXP (Java API for XML Parsing) package.

SAX XML Parser in Java
SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts. Java provides support for SAX parser and you can parse any xml file in Java using SAX Parser, I have covered example of reading xml file using SAX Parser here. One disadvantage of using SAX Parser in java is that reading XML file in Java using SAX Parser requires more code in comparison of DOM Parser.


Difference between DOM and SAX XML Parser
Here are few high level differences between DOM parser and SAX Parser in Java:

1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.

2) DOM parser is faster than SAX because it access whole XML document in memory.

3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.

4) DOM parser works on Document Object Model while SAX is an event based xml parser.


That’s all on difference between SAX and DOM parsers in Java, now it’s up to you on which XML parser you going to choose. I recommend use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you don’t know size of xml files to be processed or they are large.

Step By Step guide to Read XML file in Java Using SAX Parser Example

Read XML file in Java Using SAX Parser Example

Reading XML file in java using SAX Parser is little different than reading xml file in Java with DOM parser which we had discussed in last article of this series. This tutorial is can be useful for those who are new to the java world and got the requirement for read an xml file in java in their project or assignment, key feature of java is it provides built in class and object to handle everything which makes our task very easy. Basically this process of handling XML file is known as parsing means break down the whole string into small pieces using the special tokens.
Parsing can be done using two ways:


Using DOM Parser
Using SAX Parser

In DOM parser we have seen that we have to follow simple three steps:
Ø      Parse the XML file
Ø      Create the java object
Ø      Manipulate the object means we can read that object or add them to list or whatever function we want we can do
But in SAX Parser its little bit different.

SAX Parser: it’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls corresponding handler method.

Though there are other ways also to get data from xml file e.g. using XPATH in Java which is a language like SQL and give selective data from xml file.

Sample Example of reading XML File – SAX Parser
Suppose we have this sample XML file bank.xml which contains account details of all accounts in a hypothetical bank:

<?xml version="1.0" encoding="UTF-8"?>
<Bank>
      <Account type="saving">
            <Id>1001</Id>
            <Name>Jack Robinson</Name>
            <Amt>10000</Amt>
      </Account>
      <Account type="current">
            <Id>1002</Id>
            <Name>Sony Corporation</Name>
            <Amt>1000000</Amt>
      </Account>
</Bank>



1.      Create the SAX parser and parse the XML file:  In this step we will take one factory instance from SAXParserFactory to parse the xml  file this factory instance in turns  give us instance of parser using the parse() method will parse the Xml file.
2.      Event Handling: when Sax Parser starts the parsing whenever it founds the start or end tag it will invoke the corresponding event handling method which is public void startElement (…) and public void end Element (...).

3.       Register the events: The class extends the Default Handler class to listen for callback events and we register this handler to sax Parser to notify us for call back event

Let see java code for all these steps

To represent data from our sample xml file we need one java domain object called Account:

package parser;

public class Account {

       private String name;
       private int id;
       private int amt;
       private String type;

       public Account() {
       }

       public Account(String name, int id, int amt, String type) {
              this.name = name;
              this.amt = amt;
              this.id = id;
              this.type = type;
       }

       public int getAmt() {
              return amt;
       }

       public void setAmt(int amt) {
              this.amt = amt;
       }

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

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

       public String getType() {
              return type;
       }

       public void setType(String type) {
              this.type = type;
       }

       public String toString() {
              StringBuffer sb = new StringBuffer();
              sb.append("Account Details - ");
              sb.append("Name:" + getName());
              sb.append(", ");
              sb.append("Type:" + getType());
              sb.append(", ");
              sb.append("Id:" + getId());
              sb.append(", ");
              sb.append("Age:" + getAmt());
              sb.append(".");

              return sb.toString();
       }
}


Sample Code for implementing SAX parser in Java

package parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFileUsingSaxparser extends DefaultHandler {

       private Account acct;
       private String temp;
       private ArrayList<Account> accList = new ArrayList<Account>();

       /** The main method sets things up for parsing */
       public static void main(String[] args) throws IOException, SAXException,
                     ParserConfigurationException {
            
              //Create a "parser factory" for creating SAX parsers
              SAXParserFactory spfac = SAXParserFactory.newInstance();

              //Now use the parser factory to create a SAXParser object
              SAXParser sp = spfac.newSAXParser();

              //Create an instance of this class; it defines all the handler methods
              ReadXMLFileUsingSaxparser handler = new ReadXMLFileUsingSaxparser();

              //Finally, tell the parser to parse the input and notify the handler
              sp.parse("bank.xml", handler);
            
              handler.readList();

       }


       /*
        * When the parser encounters plain text (not XML elements),
        * it calls(this method, which accumulates them in a string buffer
        */
       public void characters(char[] buffer, int start, int length) {
              temp = new String(buffer, start, length);
       }
     

       /*
        * Every time the parser encounters the beginning of a new element,
        * it calls this method, which resets the string buffer
        */
       public void startElement(String uri, String localName,
                     String qName, Attributes attributes) throws SAXException {
              temp = "";
              if (qName.equalsIgnoreCase("Account")) {
                     acct = new Account();
                     acct.setType(attributes.getValue("type"));

              }
       }

       /*
        * When the parser encounters the end of an element, it calls this method
        */
       public void endElement(String uri, String localName, String qName)
                     throws SAXException {

              if (qName.equalsIgnoreCase("Account")) {
                     // add it to the list
                     accList.add(acct);

              } else if (qName.equalsIgnoreCase("Name")) {
                     acct.setName(temp);
              } else if (qName.equalsIgnoreCase("Id")) {
                     acct.setId(Integer.parseInt(temp));
              } else if (qName.equalsIgnoreCase("Amt")) {
                     acct.setAmt(Integer.parseInt(temp));
              }

       }

       private void readList() {
              System.out.println("No of  the accounts in bank '" + accList.size()  + "'.");
              Iterator<Account> it = accList.iterator();
              while (it.hasNext()) {
                     System.out.println(it.next().toString());
              }
       }
     
}

Output:
No of  the accounts in bank '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.



Advantage of SAX parser in Java:
It is faster than DOM parser because it will not load the XML document into the memory .its an event based.

Difference between Wait, Sleep and Yield in Java

Difference between wait and sleep or difference between Sleep and yield in Java are popular core Java interview questions and asked on multi-threading interviews. Out of three Sleep () and Yield () methods are defined in thread class while wait() is defined in Object class, which is another interview question. In this Java tutorial we will learn what is sleep in Java, important points of sleep in java and difference between Wait and sleep in Java.


Difference between Wait, Sleep and Yield in Java

Difference between Wait and Sleep in Java
Main difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting. Also wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method. Another difference is Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object. also in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state. So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.

Difference between yield and sleep in java
Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee  that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.

Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.

sleep(long millis)
or
sleep(long millis,int nanos)

Cause the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.

Example of Thread Sleep method in Java
Here is sample code example of Sleep Thread in Java. In this example we have put Main thread in Sleep for 1 second.

/*
 * Example of Thread Sleep method in Java
 */
public class SleepTest {
     
       public static void main(String... args){
              System.out.println(Thread.currentThread().getName() + " is going to sleep for 1 Second");
              try {
                     Thread.currentThread().sleep(1000);
              } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Main Thread is woken now");
       }

}

Output:
main is going to sleep for 1 Second
Main Thread is woken now



10 points about Thread sleep() method in Java
I have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:

1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.

2) Thread.sleep() method is a static method and always puts current thread on sleep.

3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as duration for sleep and other method with two arguments one is millisecond and other is nanosecond.

4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.

5) sleep() method throws Interrupted Exception if another thread interrupt a sleeping thread in java.

6) With sleep() in Java its not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.

7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t".

That’s all on Sleep method in Java. We have seen difference between sleep and wait along with sleep and yield in Java. In Summary just keep in mind that both sleep() and yield() operate on current thread.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More