Give the following code
class Test{
double x;
public void synchronized a()
{
x = 0;
//do some more stuff
}
public void b()
{
x = -1;
}
}
Can the thread in a(), in the middle of modifying x be preempted by a thread that calls b() on the same object?
Isn't synchronized method be executed like one single atomic operation?
I believe the other way is possible(thread in b() can be preempted by the thread that calls a() on the same object since b() is not guarded my the Test object lock).
Can some one shed some light on this?
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
Only one thread per instance can execute inside a synchronized instance method.
synchronized
only stops other threads from acquiring the same monitor. It in no way makes the operation atomic. In particular:
b()
isn't synchronized, so it's entirely possible for one thread to be executing a()
and another to be executing b()
at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With