Reputation: 2418
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?
Upvotes: 5
Views: 1459
Reputation: 13423
Since b()
is not synchronized and a()
is, it is possible for one thread to be in a()
and the other to be in b()
. So the value of x
will most possibly be garbled due to parallel non-synchronized access to x
.
In addition, if your code were like this:
class Test{
double x;
public void synchronized a()
{
x = 0;
//do some more stuff
}
public void b()
{
x = -1;
a(); //added call to a()
}
}
and both of your threads are running on the same instance then there arises a possibility of Thread 1 [ currently in a()
being preempted by Thread 2 [currently in b()
].
However after Thread 1 is preempted, as Thread 2 tries to enter the a()
method, the JVM will not allow it; since another thread [albeit a non running one] already has the lock on it. Hence now Thread 2 will be made to wait until Thread 1 completes execution of a()
and returns. Then Thread 2 will [most probably] be brought back to life and allowed execution of a()
.
Upvotes: 0
Reputation: 1501163
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.
Upvotes: 11