Reading here:
Without volatile it says
“then method two could occasionally print a value for
jthat is greater than the value ofi, because the example includes no synchronization and”
class Test {
static volatile int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
}
}
With volatile is says
“It is possible, however, that any given invocation of method two might observe a value for
jthat is much greater than the value observed fori, because method one might be executed many times between the moment when method two fetches the value ofiand the moment when method two fetches the value ofj.”
In behaves ‘properly’ with synchornization, but I’m confused as to what benefit volatile brings here?
I thought volatile gaurantees the order is preserved, so I would have thought it SOME cases the value of i might be greater than j, but not the other way around since that implies the order of incrementing was changed.
Is that a typo in the doc? If not, please explain how j could be greater than i when using volatile.
It is saying that in the middle of method two method one could run several and that the value read for j would be higher than the value read for i.