Preempting a thread that is executing synchronized method
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 s开发者_JAVA技巧hed some light on this?
synchronized
only stops other threads from acquiring the same monitor. It in no way makes the operation atomic. In particular:
- Side-effects of the method can be observed by other threads which aren't trying to synchronize on the same monitor
- If an exception occurs, there's no sort of roll-back
- Other threads can access and modify the same data used by the synchronized method, if they aren't synchronized on the same monitor
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.
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()
.
精彩评论