If a synchronized method calls another synchronized method, is it thread safe?
void synchronized method1() {
method2()
}
void synchronized method2() {
}
Yes, when you mark methods as synchronized
, then you are really doing this:
void method1() {
synchronized (this) {
method2()
}
}
void method2() {
synchronized (this) {
}
}
When the thread call gets into method2 from method1, then it will ensure that it holds the lock to this
, which it will already, and then it can pass through.
When the thread gets directly into method1 or method2, then it will block until it can get the lock (this
), and then it will enter.
As noted by James Black in the comments, you do have to be aware with what you do inside of the method body.
private final List<T> data = new ArrayList<T>();
public synchronized void method1() {
for (T item : data) {
// ..
}
}
public void method3() {
data.clear();
}
Suddenly it's not thread safe because you are looking at a ConcurrentModificationException
in your future because method3
is unsynchronized, and thus could be called by Thread A while Thread B is working in method1
.