Synchronized keyword is used to make the class or method thread-safe which means only one thread can have lock of synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock.

It is important to use if our program is running in multi-threaded environment where two or more threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock. Below is a simple example of Deadlock condition.

                     

Important Points :

  • If threads are waiting for each other to finish, then the condition is known as Deadlock.
  • Deadlock condition is a complex condition which occurs only in case of multiple threads.
  • Deadlock condition can break our code at run time and can destroy business logic.
  • We should avoid this condition as much as we can.

 

class MyThread{

String resource1 = "BCA";

String resource2 = "Third Semester";

void MethodA() {

synchronized (resource1) {

System.out.println("Thread 1: locked resource 1");

try { Thread.sleep(100);

}

catch (Exception e) {}

synchronized (resource2) {

System.out.println("Thread 1: locked resource 2");

}

}

}

 

void MethodB() {

synchronized (resource2) {

System.out.println("Thread 2: locked resource 2");

try {

Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {

System.out.println("Thread 2: locked resource 1");

}

}

}

}

 

public class Deadlock {

public static void main(String[] args) {

MyThread obj=new MyThread();

new Thread() {

public void run() {

obj.MethodA();

}

}.start();

 

new Thread() {

public void run() {

obj.MethodB();

}

}.start();

}

}

 

Output

Thread 1: locked resource 1

Thread 2: locked resource 2