Friday, 4 July 2014

Java Thread Tutorial

There are N number of tutorials and material  on the Internet on Threads, but i found some difficulties in terms of terminology and examples given by some of the tutorials, So i want to make it simple useful for beginners and i want to give some information points-wise that might helps to the job seeker, So lets starts with the definition of the Thread.

Thread:
   1. Thread is a light weight process.
   2. Thread is a java object it has variables and methods, it lives and dies in the   heap memory.
  3. Each thread has own call stack.

Difference between Thread and Process:

 .  Process has its own memory space and set of runtime resources(A process may contains multiple Threads or at least one Thread).
 .  Threads exist within a process.Threads share the process's                               resources,including  memory and open files.

Creating Thread:
                Thread can be created in two ways
                        1.extending Thread class
                        2. implementing Runnable interface.
extending Thread:
              class MyThread extends Thread {
                     public void run() {
                    System.out.println("Important job running in MyThread");
                       }
                   }
            in this approach we need to override the run() method as above. When Thread started running, the code in run() method will be executed.

Note: extending a Thread is not a good option, because java does not support multiple inheritence so if you extend Thread you cannot extend any other class.

implementing Runnable interface.

class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
}
}
Creating object of Thread:
           if you create a Thread by extending Thread class then instantiating is very simple as shown below:
              MyThread t = new MyThread();
         if you create a Thread by implementing Runnable interface, then instantiating is  as shown below:

 MyRunnable r = new MyRunnable();//create Runnable object and
 Thread t = new Thread(r); // Pass your Runnable to the Thread


Thread functions:
     As we discussed in point no 2. Thread is a java class, so some of its frequently used methods are:
                start()
                yield()
                sleep()
                run()

We have already seen the run() method when creating thread. So if you want to create a thread you should override the run() method, and run() method belongs to Thread class. In a little while we will see all of these methods usage.



Starting Thread: 
So far we have seen that how to create thread and how to instantiate Thread. now we are going to see how to start the Thread. To start  a thread we must invoke the start() method of the Thread class.

ex:  t.start(); here t is instance of the Thread class.


Now its time to bind all these togather:

public class ThreadSample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t = new Thread(myRunnable);// Thread is in New State
        t.start();//Thread is in Runnable State.
    }
}

class MyRunnable implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example");
            //Thread is in Running State.
        }
       
    }
   
}

Thread States: Thread always in one of the five states.

     New state
     Runnable state
     Running state
     Blocked or Wait state
     Dead state.

    New --->Runnable<----->Running------->Dead
                      \                      /
                       \                   /
                      Blocked or Waiting
New state: When the thread is instantiated

Runnable state: When thread is invoke start() method. In this state Thread is ready to run, Thread may come here from New state or Running state or from
Blocked state.

Running state: When the Scheduler pick the Thread from Runnable pool and executed the code inside run() method.

Bocked state: the thread is still alive, but is currently not eligible to run. Thread comes to this state from Running state and there are some functions in Thread class to send a Thread from Running state to Blocked state.


Dead state:
A thread is considered dead when its run() method completes. A dead thread cannot be started again.


MultiThread Example:

public class ThreadSample {
    public static void main(String[] args) {
        MyRunnableOne myRunnableOne = new MyRunnableOne();
       MyRunnableTwo myRunnableTwo = new MyRunnableTwo();
       MyRunnableThree myRunnableThree = new MyRunnableThree();

        Thread tOne= new Thread(myRunnableOne);
        tOne.start();

        Thread tTwo= new Thread(myRunnableTwo);

        tTwo.start();

        Thread tThree= new Thread(myRunnableThree);

        tThree.start();

    }
}

class MyRunnableOne implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example One");
            //Thread is in Running State.
        }
       
    }
   
}

class MyRunnableTwo implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example Two");
            //Thread is in Running State.
        }
       
    }
   
}


class MyRunnableThree implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread example Three");
            //Thread is in Running State.
        }
       
    }
   
}

 The out put would remain unexpected, for each run it would give you a different out put. When we call the start method on thread object it will enters into Runnable state and waits for its turn, Based on some criteria scheduler will pick one of the thread waiting for chance in the Runnable pool and give its time to the selected thread, When the thread is in Running it may require some i/o operations in that case scheduler sends the Running state to Blocked state.

Now its time to look into some of the Thread methods:

Sleep: Sleep() method is a static method in Thread class
try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }

Notice that the sleep() method can throw a checked InterruptedException.

When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds. After the specified time in the sleep() mehtod thread will enter into the Runnable state. So minimum time enter into the running state of Thread after sleep is (sleepTime+someTime).

i.e (5*60*1000) + some time
i.e once the specified time is over thread is enter into the Runnable state and waiting for its chance, then the scheduler will decide  when to this thread get back to Running state.


Example:

public class ThreadSample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        Thread t2 = new Thread(myRunnable);
        t1.setName("First Thread");
        t2.setName("Second Thread");
        t1.start();
        t2.start();
    }
}

class MyRunnable implements Runnable {
   
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName());
            try{
                Thread.sleep(100);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
       
    }
   
}

yield():

Thread always runs with some priority, usually the priority would be 1 to 10.
in Thread class declared some static fields as follows.


Thread.MIN_PRIORITY      (1)
Thread.NORM_PRIORITY         (5)
Thread.MAX_PRIORITY         (10)



we can set the Thread priority as
t.setPriority(8); or t.setPriority(Thread.MAX_PRIORITY);


Now the responsibility of the yield() method is moving the current running Thread to Runnable state. So the scheduler can pick another Thread which is having same or higher priority Thread and waiting for chance to get its turn from the Runnable pool.

Note: yield() method won't ever cause Thread to enter into blocked state.


      Runnable<------------------Running
                          yield()

join():
join() method is non static method of Thread class,
 ex: Thread t = new Thread();
       t.start();
       t.join();

 join() method joins the one thread to the end of the another Thread. I will explain with a simple example

 Suppose A and B are two Threads, Now i want to postponed the B execution to end of the A Thread execution.(i.e) B should be joined at the end of the A.

Example:

    public static void main(String[] args) throws InterruptedException {
        JoinThread t = new JoinThread();
        t.start();
        t.join();
        for(int i=0;i<5;i++){
            System.out.println("I am in MainThread");
        }
       
    }
   
}
class JoinThread extends Thread {
    @Override
    public void run() {
       for(int i=0;i<5;i++){
           try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
           System.out.println("I am in subThread");
       }
    }
}

In the above example There are two threads,
 1.Main Thread
 2. JoinThread.
the Main Thread will be joined at the end of the JoinThread, for testing execute the above program by commented out the t.join() line and watch the out put, i am sure you will get a different out put.

Note: t.join() method should call after starting the Thread, other wise it won't effect.(i.e) t.start(); t.join();

A little Complicated Example:

public class ThreadJoinTest {
    public static void main(String[] args) {
        ThreadOne t1 = new ThreadOne();
        Thread2 t2 = new Thread2(t1);
        Thread t = new Thread(t2);
        t.start();
      
    }
}
class ThreadOne implements Runnable{

    @Override
    public void run() {
      for(int i=0;i<20;i++){
          try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          System.out.println("Thread1");
      }
       
    }
   
}
class Thread2 implements Runnable{
    ThreadOne t1;
    Thread2(ThreadOne t1){
       this.t1 = t1;
    }
    @Override
    public void run() {
        Thread t11 = new Thread(t1);
        t11.start();
        try {
            t11.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i=0;i<20;i++){
         
            System.out.println("Thread2");
        } 
    }
   
}

here commented out  t11.join(); this line in code and see you  observe a different result.

Thread Tutorial part2

Sunday, 1 June 2014

Generics Tutorial

Generics in java have been added from java1.5, Even you don't know about generics if you have worked on collection framework in java, i am sure you should have used generics. It is possible to genirify the methods and classes in java. In this tutorial we are going to discuss about how the generics are used in java how to write generic methods and classes, lets begin with the generics in collections.

Generics in collections:

 Generics provides compile time type checking and to avoid the risk of class cast exception at run time, generic information will be lost at run time, JVM doesn't know the generic information at run time.

Let's discuss with an example, non generic collection can hold any type of object.

             List myList  = new ArrayList();
                  myList.add("bobby");//adding string object
                  myList.add("fred");//adding string object
                  myList.add(new Integer(12)); //adding ineteger object
  here you can add any type of object that doesn't complain,While retrieving the object from the collection,

               String myString = (String)myList.get(0);
 in this case cast fails at run time when   we try to retrieve the integer object from the collection. So we must do two things for non generics case
      1. it is the programmer responsibility to save a correct object type into collections
      2. while retrieving the programmer needs to do explicit cast.

  same code with generics:
           List<String> myList = new ArrayList<String>();
               myList.add("bobby");//adding string object
                  myList.add("fred");//adding string object
                  myList.add(new Integer(12)); // gives the compiler error you can't add any object other than String.
  So now using generics in collections,
      1. it is the compiler responsibility to check  and save a correct object type into collections
      2. while retrieving the programmer need not do explicit cast.
 Generics in classes:

We can declare our class as generic type. A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

Example:  public class GenericClass<T> {
    T t;
    public GenericClass(T t) {
       this.t = t;
    }
    public static void main(String[] args) {
        GenericClass<Animal> at = new GenericClass<Animal>(new Animal());
        GenericClass<Box> bt = new GenericClass<Box>(new Box());
        System.out.println(at.t);
        System.out.println(bt.t);
    }
   
}
class Animal {
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Animal class";
    }
}
class Box {
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Box class";
    }
}

output: Animal class
             Box class

Generics in Methods:
If we don't want to  use the generics in the whole class, then we can use generics  method in the class.
Example:
   public class GenericMethodAddItem {
    public static void main(String[] args) {
       ArrayList<Integer> ints = new ArrayList<Integer>();
       ArrayList<String> strings = new ArrayList<String>();
       GenericMethodAddItem gma = new GenericMethodAddItem();
       gma.addItem(2, ints);//auto boxing works here.
       gma.addItem("Raju", strings);
       for(Integer item : ints){
           System.out.println(item);
       }
       for(String item : strings){
           System.out.println(item);
       }
    }
    //add t item to the T list type.
    public <T> void addItem(T t,ArrayList<T> collection){
        collection.add(t);
    }
}

in the above example int item is added to Integer array list and string item is added String array list.
Look at once the syntax of the method. here we used angular bracket with T(i.e <T>) T specifies the type.
  for example in the above code, if you try to modify the following line as

 gma.addItem(1, strings);

 then the compiler will give you the compile time error. We cannot add int to String  array list.

Usage of Super,extend,Wild card(?) in generic methods:
As we know that in java we can assign sub type object to super type like this.
  Animal animal; //super type
  Fox fox; //subtype
  animal = new Fox();// assign sub class object to super class reference. No problem

Now:
  ArrayList<Animal> animalList = new ArrayList<Animal>();
  ArrayList<Fox> foxlList = new ArrayList<Fox>();

animalList = foxList;// We can't do this gives you the compiler error.

Here is a simple examples:

 public class GenericMethodAddItem {
    public static void main(String[] args) {
    ArrayList<Animals> animalList = new ArrayList<Animals>();
    animalList.add(new Animals());
   
    ArrayList<Fox> foxList = new ArrayList<Fox>();
    
    foxList.add(new Fox());
   
    GenericMethodAddItem gmi = new GenericMethodAddItem();
    gmi.addItem(animalList);
    //gmi.addItem(foxlList); shows the compiler error.
    //even Animals is a super type, in Animal list we cannot add sub type objects. 
}
    public <T> void addItem(ArrayList<Animals> listObjects){
        for(int i=0;i<listObjects.size();i++){
            System.out.println(listObjects.get(i));
        }
    }
}
class Animals {
    public void print(){
        System.out.println("i am animal");
    }
}
class Fox extends Animals {
    public void print(){
        System.out.println("i am fox");
    }
}

So in the above example, we cannot call the addItem() method with foxList as parameter. if we want make it work use wild card character as shown below.

i am changing the addItem method only:

public <T> void addItem(ArrayList<?> listObjects){
//listObjects.add(---) cannot add
        for(int i=0;i<listObjects.size();i++){
            System.out.println(listObjects.get(i));
        }
    }
now it will work for both animalList as well as foxList(super type and sub type).
In this case it will accept any type of list, this is know as Unbound wild card.

use of extends or upperbound wild card:
example:
public <T> void addItem(ArrayList<? extends Animal> listObjects){
//listObjects.add(---) cannot add
        for(int i=0;i<listObjects.size();i++){
            System.out.println(listObjects.get(i));
        }
    }
In this case only sub type of Animals or Animals can invoke this method. so we can call this way.
                   gmi.addItem(foxList);
here the foxList is the list of Fox objects and Fox is the sub class of Animals.

example2:
   if we want to add numbers and return sum. The numbers may be int or float or double or long.

So we can write generic method as follows:
As we know that Number is the super type of Integer,float,double,long.

public <T> int addItem(ArrayList<? extends Number> listObjects){
int sum =0;
        for(int i=0;i<listObjects.size();i++){
             sum = sum+listObjects.get(i);
        }
return sum;
    }

so you can invoke the above method like this:
1. addItem(longList);
2. addItem(integerList);
3. addItem(floatList);
4. addItem(doubleList);
 To simply say that, in place of ? any type that must be subtype of Number would accept.

Use of Super or Lowerbound:
In case of Unbound and Upperbound wildcard usage, we cannot add any new item to list in the generic method. That line has commented out in both the examples. So if we want to add an item in the list in the generic method, we must use the Super keyword as follows.

public <T> void addItem(ArrayList<? super Fox> listObjects){
          listObjects.add(new Fox()) 
        for(int i=0;i<listObjects.size();i++){
            System.out.println(listObjects.get(i));
        }
    }
we call this method like this:

  addItem(animalList);
here the animalList contains the Animal objects and Animal is the super type of Fox.













   

Saturday, 31 May 2014

Primitive types and literals in java

In Java programs you must declare variable before they are used. Variable means it holds some value. during the program execution value of the variable may be changed. Variable may be of any type, here the type is the type of value variable roining  store in it(i.e) numeric or letters or the address.

 in java types are can be divided into two:

  1. Primitive Types.

  2. Reference Types.

here we are going to discuss only about primitive types.

Primitive Types:

in java there are 8 primitive data types:

       1.boolean     (true,false)
        2.byte           (8 bits == 1 byte)
        3.short         (2 bytes == 16 bits)
        4.char          (2 bytes == 16 bits) Unicode
        5.int             (4 bytes == 32 bits)
        6.float          (4 bytes == 32 bits)
        7.long          (8 bytes == 64 bits)
        8.double      (8 bytes == 64 bits)

boolean:
              it is a one bit representation. It has only two possible values true,false
boolean t = true; // Legal
boolean f = 0;// Compiler error!


 boolean literals are  true, false.

byte: The byte data type is an 8-bit signed two's complement integer.
 
            size : 1 byte (8 bits)
          range: -128 to 127.

short: The short data type is a 16-bit signed two's complement integer
           size: 2 bytes(16 bits)

int   : the int data type is a 32-bit signed two's complement integer
            size: 4 bytes(32 bits)

long: The long data type is a 64-bit two's complement integer
            size: 8 bytes(64 bits)
 long no = 1234234L
      
byte,short,int,long are save integer type of literals.

There are three ways to represent integer numbers in the Java language:
  
   decimal(base 10)
   octal (base 8)
   hexadecimal (base 16)
   
decimal  ex: 342
            342 = 3*100+4*10+2*1 

octal  : Octal integers use only the digits 0 to 7. In Java, you represent
an integer in octal form by placing a zero in front of the number, as follows:
 ex:       int six = 06;// Equal to decimal 6
int seven = 07;// Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011;// Equal to decimal 9

hexadecimal:

Hexadecimal (hex for short) numbers are constructed
using 16 distinct symbols. Because we never invented single digit symbols for the
numbers 10 through 15, we use alphabetic characters to represent these digits.
Counting from 0 through 15 in hex looks like this:
0 1 2 3 4 5 6 7 8 9 a b c d e f
 
hexa numbers are represented as follows:
 int x = 0X0001;
 int y = 0x7f;
All three integer literals (octal, decimal, and hexadecimal) are defined as int by
default, but they may also be specified as long by placing a suffix of L or l after the number
  
char:The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).         size: 2 bytes(16 bits)
A char literal is represented by a single character in single quotes.
char a = 'a';
char b = '@';
You can also type in the Unicode value of the character, using the Unicode
notation of prefixing the value with \u as follows:
char letterN = '\u004E'; // The letter 'N'

float: The float data type is a single-precision 32-bit IEEE 754 floating point.
                    size: 4 bytes(64 bits)
   ex: float g = 49837849.029847F
 

double:The double data type is a double-precision 64-bit IEEE 754 floating point
Floating-point numbers are defined as a number, a decimal symbol, and more
numbers representing the fraction.
            size: 8 bytes(64 bits)
double d = 11301874.9881024;


** Some key points to remeber:

 1. There are 8 primitivite data types

 2. There are 4 types of literals in java

        a)integer literals--> base10,octal,hexa.
        b)char literals --> ex: 'c'(unicode representation)
        c)floating point representation: fraction numbers. 
        d)boolean representation: true, false.

3. except char remaining type are signed in java.
    signed means variable can store  positive and negative numbers.

  example byte range is -128 to 127.
  byte b = -122
  byte b = 127




 

     

         

  
        
        

Friday, 30 May 2014

Java Enum Tutorial

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Example:

public enum Month {
    JAN, FEB, MAR, APR,
    MAY, JUN, JUL,AUG,SEP,OCT,NOV,DEC
}

 here points to remeber:
 1.  enum is a keyword.
 2.  members are constants so all should be in capital.
 3. enum constants are implicitly static final.
 4. enum are introduced in java from 1.5

We can declare java constants in two ways.
 1. using enum
 2. public static final {type}

 advantages of enum over public static final.
Let me explain with a small example.
//WEEK CONSTANTS DECLARED USING final.

  public  class Day {
 public static final  MON = 1;
 public static final  TUE = 2;
 public static final  WED = 3;
 public static final  THU = 4;
 public static final   FRI =  5;
 public static final   SAT = 6;
 public static final   SUN= 7;
}
public calss WeekDay {
int weekDay ;
   weekDay = 20;
//assign 20 to weekDay.

}
 Though this can serve our purpose it has some serious limitations:
 1.No Type Safe:
     you can assign any value to weekDay. example: weekDay = 20;
      though there is no week to represent that value.
2. No namespace:

to access the WeekDay constant we need to prefix class name e.g. WeekDay.MON instead of just using MON though this can also be achieved by using static import in JDK 1.5

3.Printing:  printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print MON it will print "1" instead of "MON"

Best solution for all these limitations is enum in java.
i will explain the same example using enum.
public enum Day {
//constants for the week.
MON,TUE,WED,THU,FRI,SAT,SUN
}

public class EnumExmple {
    public static void main(String[] args) {
        Day weekDay;
  // weekDay = 20; it gives error, you can't do that here.
          weekDay = Day.MON;
//here it provides name space as well as type safe.
//type safe:       only Day constants can assign to weekDay
//name space:   to access MON only way is Day.MON.
  System.out.print(weekDay.ordinal());//prints the number
          System.out.print(weekDay);// prints MON

    }

}

Constructor with enum:

public enum Day {
MON(1),TUE(2),WED(3),THU(4),FRI(5),SAT(6),SUN(7);
int value;
  private Day(int value){
    this.value = value;
}
  public int getValue(){
      return value;
  }
}

we can write constructor in enum type as shown above.
access specifier of the constructor must be private other wise you will get compiler error. to retrieve value from the enum write a method like getValue();

Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Day.MON = Day.SUN;
The final field EnumExamples.Day.SUN cannot be re assigned.
NOTE1: you cannot create  object for the Enum type because Enum cunstructor is private and Enum constatns created inside Enums. 

NOTE2: Instance of Enum in Java is created when any Enum constants are first called or referenced in code.
enum can be used in switch :
 like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:  

        
           weekDay = Day.SUN;
            switch (weekDay) {
                    case SUN:
                            System.out.println("Sunday");
                            break;
                    case MON:
                            System.out.println("Monday");
                            break;
                    case TUE:
                            System.out.println("Tuesday");
                            break;
                    case WED:
                            System.out.println("Wednesday");
            }

    }

Enum constants can be compared:

  if(weekDay == Day.SUN){
}
loop with enum:
for(Day day: Day.values()){
                System.out.println(day); //prints enum constant as it is
                System.out.println(day.value);// prints its integer value.
            } 
 Enum with abstaract method:

public enum Day {

    MON(1, "Monday") {
        @Override
        public String getName() {
            return weekName;
        }
    },
    TUE(2,"Tuesday") {
        @Override
        public String getName() {
            return weekName;
        }
    },WED(2,"Wednesday") {
        @Override
        public String getName() {
            return weekName;
        }
    } ,THU(2,"Thursday") {
        @Override
        public String getName() {
            return weekName;
        }
    }, FRI(2,"Friday") {
        @Override
        public String getName() {
            return weekName;
        }
    }, SAT(2,"Saturday") {
        @Override
        public String getName() {
            return weekName;
        }
    },SUN(2,"Sunday") {
        @Override
        public String getName() {
            return weekName;
        }
    };
    int value;
    String weekName;

    private Day(int value, String name) {
        this.value = value;
        weekName = name;
    }

    public int getValue() {
        return value;
    }
//abstract method.
    public abstract String getName();
}

In the above example Enum constructor have two parameters

 1. int 2. String

abstract method has created anonymously as show here:
  SUN(2,"Tuesday") {
        @Override
        public String getName() {
            return weekName;
        }
    };

Enum with interface: Enum can implement interface like any class in java, By default enum implements Serialiizable  and Runnable interfaces.

public enum Day implements Runnable{
  SUN(1), MON(5), TUE(10), SAT(25);
  private int value;
  ............
        
  @Override
  public void run() {
  System.out.println("implements interface");
                
   }
}