About calling methods from a synchronized block
java, java-8, multithreading, synchronization, thread-safety
Solution
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:
- Synchronized Methods
- Intrinsic Locks and Synchronization
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)
Problem
Is synchronizing a method equivalent to letting only one thread to evaluate it until it's out of scope including inner method calls? For example: ``` public synchronized void foo(){ if(critical condition){ bar(); // can influence the above condition } baz(); // can influence the above condition } ``` Can two threads be in `bar` (suppose it's called only from here)? What if `baz` can be called from another place in the code other than `foo`, can two threads be in it then?