This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Monday, January 25, 2010

23 - Thread : deadlock - level basic - Java 1.6.0_17 - NB 6.8

A deadlock is rather easy to produce having 2 actors (2 threads) accessing 2 resources at the same time but in different order !

T1-------------T2
res A----------res B
res B----------res A

If T1 put a lock on res A, T2 put a lock on res B, then T1 tries to lock res B (waiting the lock on res B to be released) an then T2 tries to lock res A (waiting the lock put by T1 to be released). The 2 threads do not speak to each others and will wait...indefinitely... The JVM seems not able to deal with such a problem...
You have to deal with it !!!


package threaddeadlock;

public class Main implements Runnable {

    ClassA refA = new ClassA();
    ClassB refB = new ClassB();

    void operation1() throws Exception {
        synchronized (refA) {
            refA.method1();
            synchronized (refB) {
                refB.method2();
            }
        }
    }

    void operation2() throws Exception {
        synchronized (refB) {
            refB.method2();
            synchronized (refA) {
                refA.method1();
            }
        }
    }

    public void run() {
        try {
            if (Thread.currentThread().getName().equals("t1")) {
                operation1();
            } else if (Thread.currentThread().getName().equals("t2")) {
                operation2();
            } else { // should be an assertion !!!
                System.err.println("thread name must be t1 or t2 !!!");
                System.exit(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

wait forever in front of your screen... :-)


run:
t1 method1
t2 method2
BUILD STOPPED (total time: 13 minutes 30 seconds)



package threaddeadlock;

public class ClassA {

     void method1() {
        System.out.println(Thread.currentThread().getName() + " method1");
    }

}

package threaddeadlock;

public class ClassB {

     void method2() {
        System.out.println(Thread.currentThread().getName() + " method2");
    }
}



No comments:

Post a Comment

Followers