Sunday, May 8, 2016

Synchronization in Threads

Synchronization is another important section in Java. This is used to resolve data inconsistency problems in applications. 
 

What is Synchronization ?

This is the process of controlling the access of threads with shared resources. This can be obtained by using synchronized modifier.

Synchronized modifier

  • This is a modifier.
  • This can be used only with a method or a block.
  • If you declared a method or block with synchronized modifier, it allows only one thread allow to execute on the given object.

How synchronization works ?

There is a simple concept called "lock concept" of objects. You may look at the following example to understand about it.




  • Just a moment, think you want to consult a doctor for your illness.
  • When you go there, you will be able to see a waiting list (queue) with numbered order.
  • You have to get a number and then only you are allowed to consult the doctor according to number you got.



  • Then Doctor (or nurse who help doctor) call patient by patient into doctor's room and close the door while you are being consulted. It is for your privacy. 
  • When he finished, you can exit and next patient who are in the waiting list can be entered to the doctor's room.
  • This is the simple process of consulting a doctor.

Just a moment, think doctor's room is the synchronized block or method. And you are the object which wants to access that synchronized block or method. This is what happens inside the synchronized block or method.

  • When object entered to the synchronized method, thread locks that object inside the method, Then no other object can enter to this method until thread release that lock of object. 
  • At the time if another object wants to access to the synchronized method, first JVM checks about the lock. If method is locked, then JVM doesn't allow to access to this method until it release the lock.
  • If the method is not locked by the object, then JVM allow to access to that method.
  • This accruing and releasing lock is automatically done by JVM.

Synchronized or Non-synchronized ?

For an example, think about a banking system where threads are being used. In this system you may want to update a bank account in separate locations at the same time. So you can have both synchronized and non synchronized methods. You have to choose best option according to the situation.

When to use synchronized ?

  • Synchronization can be used where the state of the object is changing.
  • It means you have to use it in "add, update, delete" operations of a object.

When to use non-synchronized ?

  • You need not to have synchronization, if the sate of a object is not changing.
  • For an example in "read" operations.

Example

Look at the following example with a situation of without synchronization.

ShowMessage.java
package com.app;

public class ShowMessage {

   public void sayHello(String name) {

        for (int i = 0; i < 10; i++) {
            System.out.print("Hello ");
            try{
               Thread.sleep(500);
            }catch (InterruptedException e) {
               e.printStackTrace();
            }
            System.out.println(name);
        }
      
   }
}


MyThread.java

package com.app;

public class MyThread extends Thread {

   ShowMessage message;
   String name;

   public MyThread(ShowMessage message, String name) {
       this.message = message;
       this.name = name;
   }

   public void run() {
       message.sayHello(name);
   }

}


MainApp.java

package com.app;

public class MainApp {

   public static void main(String[] args) {

      ShowMessage msg = new ShowMessage();

      MyThread myThread1 = new MyThread(msg, "John");
      MyThread myThread2 = new MyThread(msg, "Dev");
      MyThread myThread3 = new MyThread(msg, "Ann");

      myThread1.start();
      myThread2.start();
      myThread3.start();

   }
}

When you run MainApp.java you will be able to see messed output. That is because three threads are accessing sayHello method simultaneously and it is non synchronized method. Then you can change that method into synchronized method as follows.


public synchronized void sayHello(String name){ }

Now you can see synchronized clean output. It is the way of using Synchronization in applications. But if you are running in multiple JVM environment, you need to have a global lock. At the moment I was talking about single JVM environment.


What is synchronized block ?

I think you may heard about synchronized blocks too. This can be very useful if you want to synchronize only a part of a method. If you synchronized a method, that whole method is going to be synchronized. Above example can be done using synchronized blocks. Look at below.

package com.app;

public class ShowMessage{

   public void sayHello(String name) {
     synchronized (this) {
         for (int i = 0; i < 10; i++) {
             System.out.print("Hello ");
             try{
                Thread.sleep(500);
             }catch (InterruptedException e) {
                e.printStackTrace();
             }
             System.out.println(name);
         }
      }
   }
}


This synchronized block is widely used in Singleton design pattern

In singleton pattern, this is used for double checked locking of a singleton class. Look at the following example to see how to implement it.

public class Demo {

   private volatile static Demo instance;
 
   private Demo(){ }
 
   public static Demo getDemo(){
  
      if(instance==null){ //first check
          synchronized (Demo.class) {
             if(instance==null){ //second check
                 instance = new Demo();
             }
          }
      }
   return instance;
   }
}


Advantages of synchronization

  • Data inconsistency problems can be resoled.

Disadvantages of synchronization

  • This increases waiting time of threads.
  • This creates performance problems.



Sunday, May 1, 2016

States of Threads


States of a Thread

If there is a thread, it can be in one of following states.
  • New
  • Runnable
  • Running 
  • Waiting / Blocked / Sleeping
  • Dead

New state 

In my previous post, I've mention how to create a thread(Extend Thread class or implements Runnable interface). Once you create a thread instance this instance is in this state. It means there is a thread instance which is ready to run.

Runnable state

I think you can remember how to start a thread using start() method. Once you start() a thread instance, that thread is in Runnable state but it cannot run until thread scheduler selects that instance to run. 

Running state

This is the actual running state of a thread, this state begins when the thread scheduler selects that thread to run.

Waiting / Blocked / Sleeping state

This is the state of stopping a thread from running state. Actually there are three ways as I mentioned to stop a running thread. When you run one of above methods, thread will be not in Runnable state. But it can be forwarded to Runnable state with a special treat. There are three special methods which are used in this state.

sleep()

This is static method of Thread class. Here is the method declaration. 

          public static native void sleep(long millis) throws InterruptedException;

As you can see it throws InterruptedException. Once you call sleep() method it may sleep your current thread for a given time duration that you mention in milli seconds. Look at the following example. 

Demo.java

public class Demo extends Thread {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("Demo");
            Thread.yield();
        }
    }
}


App.java

public class App{

    public static void main(String[] args){

         Demo demo = new Demo();
         Thread thread = new Thread(demo);

         try{
             thread.start();
             thread.sleep(5000);
         }catch(InterruptedException e){
             System.out.println(e.getMessage());
         }

         for(int i = 0; i < 10; i++){
             System.out.println("Main");
         }
    }
}



Once you run App.java it will print "Demo" 10 times and after 5s it will print "Main".

Yield()

This can be used when a thread wants to pass its execution to give the chance for other remaining threads with same priority.


                  public static void yield()

It means yield() method change the state of currently executing thread to runnable state. But this is depend on the platform, if you want to use this in a proper way, you have to have supportive underlying processor. Otherwise you may get confusing results. It means output cannot be guaranteed. Look at the following example.


Demo.java

public class Demo extends Thread {

   @Override
   public void run() {

       for (int i = 0; i < 5; i++) {
          System.out.println("Demo");
          Thread.yield();
       }
   }
}



App.java

public class App {

   public static void main(String[] args) throws InterruptedException{

       Demo demo = new Demo();
       demo.start(); 
   
       for(int i = 0; i < 5; i++) {
           System.out.println("Main");
       }
   }
}


join()


           public final void join( ) throws InterruptedException


Simply join() method can be used to stop executing current thread and wait until other thread get executed. Remember that if you are using join() method, it is compulsory to handle InterruptedException. Look at the following example.

Demo.java

public class Demo extends Thread {

   @Override
   public void run(){

       for(int i = 0; i < 5; i++){
           System.out.println("Demo");

           try{
               Thread.sleep(200);
           }catch(InterruptedException e){
               e.printStackTrace();
           }
       }
   }
}

App.java

public class App{

   public static void main(String[] args)throws InterruptedException{

       Demo demo = new Demo();
       demo.start(); 
       demo.join(); 
  
       for(int i = 0; i < 5; i++){
           System.out.println("Main");
       }
   }
}

Dead state

This is the end of a thread instance, once it becomes dead, it cannot be alive again.




I think now you've got some idea about the states of a thread. In next post I'l move with other related advanced theories in threads.