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?
synchronizedonly 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 executinga()and another to be executingb()at the same time.