What is the purpose of multilevel synchronization?
I don't really understand what is the purpose of the multilevel synchronized operator? For example, 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 not possible to execute the most restrictive synchronized statement for any thread if some thread has already started executing it. Thus, I do not see any benefit from such construction. Could you provide an example to understand this usage?
Another example of nested synchronized operators can be found in the official JLS specs: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.19
From OP's comments, this comes from JLS §14.19
class Test {
public static void main(String[] args) {
Test t = new Test();
synchronized(t) {
synchronized(t) {
System.out.println("made it!");
}
}
}
}
The JLS continues:
Note that this program will block if one thread is not allowed to lock the monitor more than once.
This example is intended to illustrate that blocks synchronized
are reentrant.
This JLS is not a document of useful coding techniques .
It is impossible to illustrate how the language is supposed to work. It documents language constructs and defines their behavior - this is a specification.
source to share