I was told that the following code example has a data race condition (assuming multiple threads, of course):
class C {
private int x = 0;
private int y = 0;
void f() {
x = 1;
y = 1;
}
void g() {
int a = y;
int b = x;
assert(b >= a);
}
}
Yet, I am told that the following "fix" does not have data races:
class C {
private int x = 0;
private int y = 0;
void f() {
synchronized(this) { x = 1; }
synchronized(this) { y = 1; }
}
void g() {
int a, b;
synchronized(this) { a = y; }
synchronized(this) { b = x; }
assert(b >= a);
}
}
Understandably, there are other problems with the above examples, but I just want to know why the second code block has no race conditions. How does synchronizing each assignment statement eliminate the data race condition? What is the significance of synchronizing only a single assignment statement at a time?
Just to clarify, data race is defined as such:
Data races: Simultaneous read/write or write/write of the same
memory location