Java – deliberately cause Deadlock

Tuesday, August 4th, 2015

Another interview question.

When this code is executed runnable1 will wait for a lock on “b” and runnable2 will wait for a lock on “a”.

package test;
/**
 * Deliberately try and cause deadlock
 * 
 */
public class DeadLockTest {
    public static void main(String[] args) {
    	final Object a = new Object();
        final Object b = new Object();
 
        final Runnable runnable1 = new Runnable() {
            public void run() {
                synchronized (a) {
                    try {
                        Thread.sleep(100); // Adding delay to increase chance of deadlock
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    synchronized (b) { // We already have "a" abut need "b" too
                        System.out.println("In runnable1");
                    }
                }
            }
        };
 
        final Runnable runnable2 = new Runnable() {
            public void run() {
                synchronized (b) { // Has "b" but needs "a"
                    synchronized (a) {
                        System.out.println("In runnable2");
                    }
                }
            }
        };
 
        new Thread(runnable1).start();
        new Thread(runnable2).start();
    }
}

You can leave a response, or trackback from your own site.

Tags:
Posted in: Interview Questions



Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>