I really don't understand what purpose of multiple-level synchronized statement? For instance, in the code:
static void m() throws Exception {
synchronized (sync) {
System.err.println("First level synchronized");
synchronized (sync) {
System.err.println("Second level synchronized");
synchronized (sync) {
System.err.println("Third level synchronized");
}
}
}
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
@Override
public void run() {
try {
m();
} catch (Exception ex) {
Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
Thread th1 = new Thread(r);
Thread th2 = new Thread(r);
th1.run();
th2.run();
}
It is impossible to execute the most-enclosing synchronized statement for any thread if some thread has already started to execute one. So, I cannot see any usefulness of such construction. Could you provide an example to understand such using?
An other example of nested synchronized statements can be found in the official JLS specs: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.19