Reputation: 281
Suppose I have a class where in the have methods synchronized in the way as follows.
public class Test{
public static synchronized void method1(){
}
public static synchronized void method2(){
}
public synchronized void method3(){
}
public synchronized void method4(){
}
}
So there is a scenario when two threads are calling method1
and method2
simultaneously.I feel that only one of the methods be allowed to call.What will be the case if they call method1
and method3
.Will there be a same scenario here too?what will be the case with method3
and method4
from same object?
Upvotes: 2
Views: 104
Reputation: 6075
By using synchronized on a static method you will synchronize on the Class object. So basically only one synchronized method can be run from different threads. The one that can't acquire the lock will wait for the first method to finish
Normal method do synchronize on the instance. So a static method and a non static method can be run at once by different threads. 2 different non static synchronized methods won't run at once if one method is called from different threads. One method will wait for the first to finish
So:
method1 and method2 won't run at the same time if they are called from different threads
method3 and method4 won't run at the same time if they are called from different threads
method1 and method3 will run at the same time if they are called from different threads (same for method2 and method 4)
Upvotes: 0
Reputation: 26175
If you have two objects of class Test, referenced by x and y, there will be three monitors, one for Test, one for x, and one for y.
method1 and method2 both use the Test monitor, and so exclude each other. method3 and method4 each use the monitor for their target object, so they exclude each other if called for the same object, but not if called for different objects. They don't involve the Test monitor, so they don't exclude the static methods.
Upvotes: 5
Reputation: 8354
threads trying to call synchronized static and non-static methods will never block each other.
a thread calling method1
and method2
will be locked on Test.class
, while formethod3
and method4
it will be locked on this
.
so threads calling method1
and method3
won't block each other , while threads calling method3
and method4
will block each other if they use the same instance of Test
.
Upvotes: 0
Reputation: 1444
So there is a scenario when two threads are calling method1 and method2 simultaneously.I feel that only one of the methods be allowed to call
This does not make any sense to me.
A single thread can call only one method at a time.On the other hand a single method can be called by multiple threads.
Upvotes: 0