Reputation: 200196
Consider a simple, single-threaded Java program execution involving no synchronization actions, just plain reads and writes of instance variables. An implementation that simply ignores all writes seems to comply with the Java Memory Specification. First, the applicable general statement from §17.4:
The memory model determines what values can be read at every point in the program. The actions of each thread in isolation must behave as governed by the semantics of that thread, with the exception that the values seen by each read are determined by the memory model.
The relevant constraints would be the following (§17.4.5):
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
A set of actions A is happens-before consistent if for all reads r in A, where W(r) is the write action seen by r, it is not the case that either hb(r, W(r)) or that there exists a write w in A such that w.v = r.v and hb(W(r), w) and hb(w, r).
This basically precludes a read happening-before the write it observes. The other provision is just a sanity clause that prevents a read of some v
seeing an earlier write of that v
that was in the meantime followed by another write of the same v
.
I cannot find any guarantee whatsoever that a write will positively be observed, only restrictions on what writes may not be observed.
What am I missing here? Is it really possible that the JVM leaves out such a trivial guarantee?
Upvotes: 5
Views: 296
Reputation: 328737
Let's use:
class MyClass {
private static int i = 0;
public static void main(String[] args) {
i = 3; //w
System.out.println(i); //r
}
}
When a program contains two conflicting accesses (§17.4.1) that are not ordered by a happens-before relationship, it is said to contain a data race.
Your program is single threaded
=> we have hb(w,r) from the program order constraint
=> it is correctly synchronized
=> all executions of the program will appear to be sequentially consistent.
=> it will print 3
Upvotes: 4