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 already has, and thus it can pass through.
Now when another thread tries to get directly into method1 or method2, then it will block until it can get the lock (this), and only then it will enter into any of the two methods.
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.