简体   繁体   中英

About calling methods from a synchronized block

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?

Can two threads be in bar (suppose it's called only from here)?

Yes, provided they are using different objects, or one is wait() ing.

What if baz can be called from another place in the code other than foo, can two threads be in it then?

Yes, placing synchronized on one method has no effect on methods which are not synchronized.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM