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.