Tuesday, 27 May 2014

Example of deadlock

Following is the simplest example of how deadlock occurs?. Following code will run forever since they are waiting for each other to release the lock.

public static void main(String[] args) {
        // TODO Auto-generated method stub
        final LinkedList<String> ll_1=new LinkedList<String>();
        final LinkedList<String> ll_2=new LinkedList<String>();
       

        //first thread
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                synchronized (ll_1) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized (ll_2) {
                       
                    }
                    }
            }
        }).start();
       
        //second thread
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                synchronized (ll_2) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized (ll_1) {
                       
                    }
                    }
            }
        }).start();
    }

No comments:

Post a Comment