views:

46

answers:

2

I am a newbie to J2EE. I wonder if there are some common deadlock cases in J2EE application layer, resulting from using Java synchronization primitive - synchronized keyword. If yes, could help give an example? Thanks a lot!

A: 
public void myMethod1() throws Exception {
    synchronized (MyClass.class) {

        Thread.sleep(10*1000);

        synchronized (MyClass2.class) {
        }
    }
}

public void myMethod2() throws Exception {    
    synchronized (MyClass2.class) {

        Thread.sleep(10*1000);

        synchronized (MyClass1.class) {
        }

    }
}

Call myMethod1 from one thread and myMethod2 from other thread and you will get a deadlock.

Faisal Feroz
A nice example! Is it common in servlet or EJB? Or it just happens in J2SE applications?
Daniel Luo
This can happen in any case. The thing to note here is that we are taking locks in reverse order. When locks are taken, we should always take locks in predetermined/same order so that deadlocks don't happen.
Faisal Feroz
+1  A: 

From the EJB 3.1 spec, Chapter 21.2.2. Programming Restrictions:

An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances, except if it is a Singleton session bean with bean-managed concurrency.

And the reasoning is also interesting:

Synchronization would not work if the EJB container distributed enterprise bean’s instances across multiple JVMs.

Gabor Kulcsar