Java Synchronized with Examples

Last updated on February 27th, 2024

In this topic, we will learn what Java Synchronized is and how to use it with examples. In Java Synchronized is a keyword. It marks a block or method in the code. This keyword is used where we need thread safety. After using this keyword one thread is executing at a time which holds the lock. 
This keyword is used on:-
• Block
• Method

Example of a program without a Synchronized 

In this example, we can create a Test class which is having printNum method to print numbers as per the passing parameter to this method.

class Test{
public void printNum(int n) throws InterruptedException{
for (int i = 1; i <= n; i++){
System.out.println(Thread.currentThread().getName() + " : "+ i);
Thread.sleep(500);
  }
 }
}
public class Main{
public static void main(String args[]){
Test test = new Test();
Runnable r = new Runnable(){
public void run(){
try{
test.printNum(5);
}catch(InterruptedException e){
e.printStackTrace();
   }
 }
};
new Thread(r, "Thread1").start();
new Thread(r, "Thread2").start();
 }
}

Output

Thread2 : 1
Thread1 : 1
Thread2 : 2
Thread1 : 2
Thread2 : 3
Thread1 : 3
Thread2 : 4
Thread1 : 4
Thread2 : 5
Thread1 : 5

→ In the above example, we have seen the output of the example Thread2 is executed first and not completed its job. Thread1 does not wait for Thread 2 to complete its job first and Thread1 is also executed. If we will run this program again it gives different output. 
→ If we want to need thread safety of this program we will use the synchronized keyword as shown below of the program with synchronized block and method.

Java Synchronized Block

When we are using a synchronized keyword in the block then it is called a synchronized block in Java.
Syntax

synchronized(object){
 //synchronized statements
}

→ In the above syntax “object” is a reference to the object which holds a lock associated with the monitor.

Example of Java Synchronized Block

In this example, we can create a Test class which is having printNum method to print numbers as per the passing parameter to this method and use a synchronized block.

class Test {
  public void printNum(int n) throws InterruptedException {
    synchronized(this) {
      for (int i = 1; i <= n; i++) {
        System.out.println(Thread.currentThread().getName() + " : " + i);
        Thread.sleep(500);
      }
    }
  }
}

public class Main {
  public static void main(String args[]) {
    Test test = new Test();

    Runnable r = new Runnable() {
      public void run() {
        try {
          test.printNum(5);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    };

    new Thread(r, "Thread1").start();
    new Thread(r, "Thread2").start();
  }
}

Output

Thread1 : 1
Thread1 : 2
Thread1 : 3
Thread1 : 4
Thread1 : 5
Thread2 : 1
Thread2 : 2
Thread2 : 3
Thread2 : 4
Thread2 : 5

→ In the above example, we have seen the output of the example Thread1 is executed first and completed its job. Then Thread2 is executed and completed its job.
→ In the above program, we used thread safety with a synchronized block.

Java Synchronized Method

When we are using a synchronized keyword in the method then that method is known as a synchronized method in Java.

Syntax

<access_modifier> synchronized method(parameters){
 //body
}

Example of Java Synchronized Method

In this example, we can create a Test class which is having printNum method to print numbers as per the passing parameter to this method and use a synchronized method.

class Test {
  public synchronized void printNum(int n) throws InterruptedException {
    for (int i = 1; i <= n; i++) {
      System.out.println(Thread.currentThread().getName() + " : " + i);
      Thread.sleep(500);
    }

  }
}

public class Main {
  public static void main(String args[]) {
    Test test = new Test();

    Runnable r = new Runnable() {
      public void run() {
        try {
          test.printNum(5);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    };

    new Thread(r, "Thread1").start();
    new Thread(r, "Thread2").start();
  }
}

Output

Thread1 : 1
Thread1 : 2
Thread1 : 3
Thread1 : 4
Thread1 : 5
Thread2 : 1
Thread2 : 2
Thread2 : 3
Thread2 : 4
Thread2 : 5

→ In the above example, we have seen the output of the example Thread1 is executed first and completed its job. Then Thread2 is executed and completed its job.
→ In the above program, we used thread safety with the synchronized method.

Example of Java Synchronized Static Method

In this example, we can create a Test class which is having printNum method to print numbers as per the passing parameter to this method and use a synchronized static method.

class Test {
  public synchronized static void printNum(int n) throws InterruptedException {
    for (int i = 1; i <= n; i++) {
      System.out.println(Thread.currentThread().getName() + " : " + i);
      Thread.sleep(500);
    }

  }
}

public class Main {
  public static void main(String args[]) {

    Runnable r = new Runnable() {
      public void run() {
        try {
          Test.printNum(5);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    };

    new Thread(r, "Thread1").start();
    new Thread(r, "Thread2").start();
  }
}

Output

Thread1 : 1
Thread1 : 2
Thread1 : 3
Thread1 : 4
Thread1 : 5
Thread2 : 1
Thread2 : 2
Thread2 : 3
Thread2 : 4
Thread2 : 5

→ In the above example place lock on the class, not on the object.

Conclusion

In this topic, we learnt about what is a Java Synchronized keyword and how to use this keyword in the program.

Leave a Comment