Synchronization in Java

Synchronization in Java

  • Synchronization is the modifier applicable  only for methods and blocks but not for classes and variables.
  • If multiple threads are trying  to operate simultaneously on the same java object, then there may be a chance of data inconsistency problem.
  • To overcome this problem, we should go for synchronized keywords.
  • If a method or block declared as synchronized than at a time only one thread is allowed to execute that method or block on the given object.
  • The main advantage of synchronized keyword is, we can resolve data inconsistency problems. 
  • But the main dis-advantage of this is, it increases waiting time of thread and create performance problem.
  • Hence there is no specific requirement, then its not recommended to use this keyword.


Internal working of synchronized keyword

  • Internally synchronization concept is implemented by using lock.
  • Every object in java has a unique lock.
  • Whenever we are using synchronized keyword then only lock concept will coming to the picture. 
  • If a thread want to execute synchronized method on the given object, first is has to get lock of that object.
  • Once thread got the lock then it is allowed to execute any synchronized method on that object.
  • Once method execution completes automatically thread release lock.
  • Acquiring and releasing lock internally take care by JVM and programmer not responsible for this activity.
  • While a thread executing synchronized method on the given object, the remaining thread are not allowed to execute any synchronized method simultaneously on the same object.
  • But remainig threads are allowed to executing not synchronized method simultaneously.
 
 
synchronized kwyeord in thread java
synchronized keyword in java
Synchronized in java

Synchronized examle in java


Note: 

  • If  multiple thread are operating on same java object then synchronized is required.
  • If multiple thread are operating on multiple java object then synchronized not required.

 Class level lock: 

  • Every java class has a unique lock (known as: Class level lock).
  • If a thread wants to execute static synchronized method, then thread required class level lock.
  • Once Thread got class level lock, then it is allowed to execute any static synchronized method of that class.
  • After method execution complete, thread automatically release the lock.

While a thread executing static synchronized method, then remaining thread are not allowed to execute static synchronized method of that class simultaneously but remaining thread are allowed to execute the following method simultaneously.

  1. Normal static method
  2. synchronized instance method
  3. Normal instance method 

  

Synchronized keyword in java

Ex:

class Test 
   public static void main(String agra[]) 
   {
    Demo d = new Demo();
        
        MyThread1 t1 = new MyThread1(d);
        MyThread2 t2 = new MyThread2(d);        
        t1.start();
        t2.start();
 }
 
class MyThread1 extends Thread
{
    Demo d;
    MyThread1(Demo d){
        this.d=d;
    }   
    public void run() {
        d.demo1();
    }
}
class MyThread2 extends Thread
{
    Demo d;
    MyThread2(Demo d){
        this.d=d;
    }   
    public void run() {
        d.demo2();
    }
}

class Demo
{
    public static synchronized void demo1()
    {
        for(int i=0; i<5;i++) {
            System.out.println(i);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {                 
                e.printStackTrace();
            }
        }
    }
    public synchronized void demo2()
    {
        for(int i=65; i<=70;i++) {
            System.out.println((char)i);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {                 
                e.printStackTrace();
            }
        }
    }   
}
 

Output

method demo1() and demo2() run when one method complete their execution. 

Note:

When make only one method as  static either demo1() or demo2() then both method run simultaneously.

Synchronized block 

  • If very few lines of code required synchronization then it is  not recommended to declare entire method as synchronized.
  • We have to enclose those few lines of the code by using synchronized block.
  • The main advantage of synchronized block over synchronized method is, it reduce waiting time of thread and improve performance of program. 

Syntax:

 To get lock of current object

synchronized (this)
{
    // If a thread got lock of current thread object then only it is allowed to execute this area.
}

  To get lock of particular object 'obj'

synchronized (obj)
{
    // If a thread got lock of particular thread object 'obj' then only it is allowed to execute this area.
}

To get lock of current object

synchronized (Demo.class)
{
   // If a thread got class level lock of 'Demo' class then only it is allowed to execute this area.
}

Ex:

public class Test 
  public static void main(String[] args) 
 { 
  Demo d = new Demo(); 
  MyThread1 t1 = new MyThread1(d,"Rakesh"); 
  MyThread1 t2 = new MyThread1(d,"Raka"); 
  t1.start(); 
  t2.start(); 
 } 
}
class MyThread1 extends Thread
{
    Demo d;
    String name;
    MyThread1(Demo d, String name){
        this.d=d;
        this.name = name;
    }
    
    public void run() {
        d.demo1(name);
    }
}

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

Output

Both thread access synchronized block one by one. Means first complete after that second access it.

Imp Note:

  • Lock concept available for object type and class types but not for primitives, hence we cannot pass primitive type as arguments to synchronized block, otherwise we will get compile time error.
  • If multiple operate simultaneously on same object then there may be a chance of data inconsistency problem. This is called Race condition. We can overcome this problem by using synchronized keyword.
  • The statement present in synchronized method and synchronized block are called synchronized statement.
  • A thread  can acquire multiple lock simultaneously from different object.
Synchronized keyword importance



 

RAKESH RAKA

I am Rakesh Raka, senior software engineer (JAVA) in Sopra Steria.

2 Comments

  1. Great work. I am also in sopra but I did not find you on teams.

    ReplyDelete
    Replies
    1. Hi Aman, Thanks for your comment. Please search me in teams with name "Rakesh Yadav". You can definitional find me (smile.)

      Delete
Post a Comment
Previous Post Next Post