How to avoid deadlocks in Java Threads


 Deadlock in Java
When there are multiple threads being executed in a Java application then there is also the need for synchronization of mutually exclusive code. The use of synchronization often leads to deadlock in Java, if not properly implemented.
Deadlock in Java application is a situation when the execution can not proceed further because multiple threads are waiting for other threads to release locks. There is a kind of cyclic inter-dependency between threads where the first thread is waiting for second thread to release lock and the second thread is waiting for third thread to release lock and so on. The last thread in the cycle in waiting for the first thread to release lock on a particular resource/object.
Usually, deadlock in java doesn’t occur on their own and the most common reason is the improper usage of synchronization blocks and methods in Java.

How deadlock in Java gets created
I will show an example code to create a deadlock in Java program in which I will simulate the deadlock situation. This is also sometimes required for Java interview where the candidate is asked to write a sample code to create deadlock.
package com.example;

public class Test extends Thread{
    public static void myMethod1(){
        synchronized(Test.class){
            System.out.println("Test locked");
            synchronized (String.class) {
                System.out.println("String locked");
            }
       }
    }

    public static void myMethod2(){
        synchronized(String.class){
            System.out.println("String locked");

            synchronized (Test.class) {
                System.out.println("Test locked");
            }
        }
    }

    public void run() {
        if(Thread.currentThread().getName().equals("Thread 1")){
            myMethod1();   
        } else {
            myMethod2();   
        }
    }

    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test();
        t1.setName("Thread 1");
        t1.start();
        t2.start();
    }
}

Output:
Test locked
String locked
After printing the above to console, both threads t1 and t2 will keep on waiting for each other.
Related Post:-   
How to find if deadlock has occurred 

People who read this post also read :



2 comments:

make MyMethod2() has same order as Mymethod1()

Did you know that you can earn dollars by locking special pages of your blog or website?
Simply join AdscendMedia and add their content locking plug-in.

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More