This is an equivalent way of writing your code:
public void foo(){
synchronized (this) {
if(critical condition){
bar(); // can influence the above condition
}
baz(); // can influence the above condition
}
}
Because synchronized methods actually synchronize their bodies using this
as the lock object.
So, can two threads be executing foo()
at the same time or bar()
at the same time? Sure, if they are executing the foo()
or bar()
of different objects.
Also, the call to baz()
is not synchronized at all, so even any two threads can run the baz()
of single object at the same time, as long as at least one of them is invoking it from outside foo()
.
These two resources are useful for understanding what synchronization does and doesn't do in Java:
I recommend you check those pages because there are some pieces of information that are not too obvious until you check them. For example:
- Two different threads cannot execute at the same time two different synchronized methods of a single object.
- A single thread can be executing two different synchronized methods of the same object (called Reentrant Synchronization)
bar()
andbaz()
, one thread will takethis
as the lock and use it through bothbar
,baz
till the end offoo
and only one thread? – Mime