Reputation: 837
public class Check {
public boolean toChange = false;
public synchronized boolean getChange() {
return tochange
}
public synchronized setChange(boolean change) {
this.tochange = change
}
}
When 2 different threads try to access get and set simultanoesuly , will it happen in a synchronous way due to lock on check object?
Upvotes: 0
Views: 45
Reputation: 68975
Only one thread can hold the lock of the object. And then it's only that thread that can enter the synchronized methods on that object.No other threads can access any of the synchronized methods of that object.
The thread can however release the lock without returning from the method, by calling
Object.wait()
Other thread will be on blocked state till the first thread releases the lock over the instance of Check object.Also note any Thread can enter a method of the class that does not synchronize on the object.
So the answer is Yes two different threads cannot access get and set method simultaneously.
Upvotes: 0
Reputation: 17622
Since both the methods are non-static and synchronous, no 2 threads at any instance of time, can execute both the methods simultaneously, IF they belong to same INSTANCE.
So yes, it will happen in a synchronous way, within instances of this class.
When you create Check c = new Check();
and 2 threads namely t1, t2
try to access c.getChange()
and c.setChange()
simultaneously, only one thread will be given the access to monitor (which is instance c
) and the other thread has to wait until the previous thread finishes work and releases the monitor.
Here the instance c
is the default monitor used to synchronize the access
Upvotes: 4