The code is simple.
// not annotated with volatile
public static int I = 0;
public static int test(){
I = 1;
return I;
}
There is a thread that invokes the method test.
Is it possible the method test will return the value '0'?
In other words, the reading of a shared variable maybe not see the modifying by the same thread.
The question just very simple, but I make its obscurity, I'm really sorry about it.
The a thread means a single thread.
And the question is duplicated with it.
Any answer that does not explain in terms on java language specification is only partially correct, if correct at all.
You need to make a clear distinction between actions that happens within a single thread and are tied together by program order and that in turn creates a happens-before connection, specifically via:
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
That rule tells you that if you think about this code in single threaded world, it will always print 1.
And on the other hand, actions that create synchronizes with connections across different threads, and implicitly those create happens-before, via:
If an action x synchronizes-with a following action y, then we also have hb(x, y).
In your case, I is a plain field, as such every operation related to it is a plain store and/or a plain load. Such stores and loads do not created any connections at all according to the JLS. As such some thread that reads I can always read it as 0 if there is a writing thread involved.
No, it will be 1 if no other thread is involved but the one that will invoke the method.
chrylis -cautiouslyoptimistic's answer is worth reading for an alternative scenario as well.
Two reasons:
I is just altered by its owner, and if the other thread just calls test(), there's no option for it to get a 0 as I's value.Class.I's value, but the result of the test() method. The assignation I=1 happens before the return so is guaranteed to offer the latest updated value (which has only been updated by the owner, once).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With