Skip to content
Advertisement

If a method is synchronized, do the called methods also have to be synchronized?

If a method is synchronized, do the called methods also have to be synchronized? What is correct in the following example?

// Only parent method synchronized 
public synchronized void parentMethod() {
    childMethod1();
}

public void childMethod1() {
    childMethod2();
}

public void childMethod2() {
    
}



// All methods synchronized 
public synchronized void parentMethod() {
    childMethod1();
}

public synchronized void childMethod1() {
    childMethod2();
}

public synchronized void childMethod2() {
    
}

Advertisement

Answer

If a method is synchronized, do the called methods also have to be synchronized?

No.

There is no general reason that you need to call a synchronized method from another synchronized method.

Assuming that the methods are synchronizing on the same object then all patterns are valid, depending on what you are trying to achieve:

  • calling a synchronized method from a synchronized method
  • calling a synchronized method from a plain method
  • calling a plain method from a synchronized method
  • calling a plain method from a plain method

In all but the last case, the called method will hold the lock on the target object.

(In the first case, it appears as if the thread is going to the same object twice. In fact, Java primitive locks are re-entrant … so this is not a problem.)


If the method calls were on different target objects, it gets a bit more complicated. Now you have to consider whether your application requires both objects to be locked. Also you need to consider the possibility of deadlocks. (If two threads attempt to simultaneously acquire the same two primitive locks, but in a different order, you will get a deadlock.)


It is not actually possible to give hard rules about which methods need to be synchronized1. It depends on what the methods do, and whether you are using primitive lock mutexes or some other mechanism (Lock, volatile, immutable types, etc) to synchronize and/or ensure memory visibility. And even for primitive lock mutexes, you can either use synchronized methods of synchronized blocks to achieve the same thing.


1 – Note that the question doesn’t ask this anyway!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement