user2953119
user2953119

Reputation:

What is the purpose of multiple-level synchronized statement?

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

Upvotes: 3

Views: 68

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61178

From the OP's comments this comes from the 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 goes on to say:

Note that this program would deadlock if a single thread were not permitted to lock a monitor more than once.

This is example is meant to illustrate that synchronized blocks are reentrant.

This JLS is not a document of useful coding practices.

It is desgined to illustrate how the language is supposed to work. It documents language constructs and defines their behaviour - it is a specification.

Upvotes: 7

Alan Stokes
Alan Stokes

Reputation: 18974

It's an example of something that is legal, not something that is useful or recommended. It's showing that the lock is recursive ("Note that this program would deadlock if a single thread were not permitted to lock a monitor more than once").

Upvotes: 2

Related Questions