Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 313
shinzou Avatar asked Oct 16 '16 15:10

shinzou


People also ask

Which method is used in synchronized block?

When thread enters into synchronized instance method or block, it acquires Object level lock and when it enters into synchronized static method or block it acquires class level lock. Java synchronization will throw null pointer exception if Object used in synchronized block is null.

Why must wait () method be called from the synchronized block?

Note also that wait() forces the thread to release its lock. This means that it must own the lock of an object before calling the wait() method of that (same) object. Hence the thread must be in one of the object's synchronized methods or synchronized block before calling wait().

What happens when synchronized method is called?

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

Can a synchronized method call another synchronized method?

Yes , we can call any number of synchronized method within any synchronized method , it will work as stack how normal method works because when we make any method as synchnonized then lock is over class and thread which owns this lock is running all these methods so there is mens of conflict..


1 Answers

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.

like image 191
Peter Lawrey Avatar answered Oct 10 '22 01:10

Peter Lawrey