问题
I am a newbie to Java EE. I wonder if there are some common deadlock cases in Java EE application layer, resulting from using Java synchronization primitive - synchronized keyword. If yes, could help give an example?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/3793135/thread-deadlock-in-java-ee-application