Search code examples
javamultithreadingsynchronizationjava-threads

Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method?


In Java using the synchronized keyword all within a single object and thread.

Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method, without the final synchronized method blocking for the first synchronized method to be completed?


Solution

  • Your code can always call a method whether it is synchronized or not. A better question is, what will happen when your code calls it.

    A synchronized method that looks like this:

    synchronized void foobar() {
        doSomething();
    }
    

    Actually is just a short-hand way of writing this:

    void foobar() {
        synchronized(this) {
            doSomething();
        }
    }
    

    So any question about calling a synchronized method really is a question about executing a synchronized block. There are three things that could happen when your code enters synchronized(this) {...}.

    1) If the this object is not locked, then it will be locked in the name of the calling thread, the thread will execute the statements in the block, and then it will unlock the lock when it's done.

    2) If the this object already has been locked by the calling thread, then the thread will simply execute the statements in the block.

    3) If the this object is locked by some other thread, then the calling thread will wait until the other thread unlocks it, and then it will proceed as in case (1).

    The only way you can get into trouble is if your code attempts to lock two different locks. Then, if your design is not well thought out, two or more threads could deadlock, which is something you can read about elsewhere.