I have a concurrent program that needs bait of clarification. The first program is considered Atomic whereas the second isn’t.
NOTE: The // don’t mean comments here – they mean that it is another process executing concurrently with the other.
Here is the first:
int x = 0, y = 0;
co
x = y + 1; // y = y + 1;
oc
The program above can be regarded as atomic – but I don’t understand why this is. But this next program isn’t.
int x = 0, y = 0;
co
x = y + 1; // y = x + 1;
oc
I know that an atomic action is a programming instruction that changes the state of a computer system indivisibly and also know that loading and storing values from/to a register is a typical atomic action. So whats going on above?
In your first case you will always encounter
yeither before or after the increment. Since operations are async you can’t tell which, but it doesn’t make any difference — the only observable effect is thatxis larger by 1 in one case rather than the other, and this could have occurred based on ordering of the two statements.In the second case, you can get a situation where the resulting values of x and y are not consistent with either ordering of the statements, because x and y were both fetched before either was modified.
The first case is not really Java’s definition of “atomic” (and has nothing to do with any “atomic” directives that might be generated by the compiler), but simple programming.