Wednesday, 29 March 2017

DeadLock in Java Thread


class WorkerThread implements Runnable {
public void run(){
method1();
method2();
}

/*
     * This method request two locks, first String and then Integer
     */
    public void method1() {
        synchronized (String.class) {
            System.out.println(Thread.currentThread().getName() + ":Aquired lock on String.class");

            synchronized (Integer.class) {
                System.out.println(Thread.currentThread().getName()+":Aquired lock on Integer.class");
            }
        }
    }

    /*
     * This method also requests same two lock but in exactly
     * Opposite order i.e. first Integer and then String.
     * This creates potential deadlock, if one thread holds String lock
     * and other holds Integer lock and they wait for each other, forever.
     */
    public void method2() {
        synchronized (Integer.class) {
            System.out.println(Thread.currentThread().getName() + ":Aquired lock on Integer.class");

            synchronized (String.class) {
                System.out.println(Thread.currentThread().getName()+":Aquired lock on String.class");
            }
        }
    }
}

public class DeadLockPrac {
public static void main(String[] args) {
WorkerThread wt = new WorkerThread();
Thread t1 = new Thread(wt);
Thread t2 = new Thread(wt);
t1.start();
t2.start();
}
}

No comments:

Post a Comment

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...