简体   繁体   中英

Does the Java Memory Model guarantee visibility of intra-thread writes?

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 ):

1. happens-before ordering induced by program order:

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

2. happens-before consistency:

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 wv = rv 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?

Let's use:

class MyClass {
    private static int i = 0;

    public static void main(String[] args) {
        i = 3; //w
        System.out.println(i); //r
    }
}
  • A program is correctly synchronized if and only if all sequentially consistent executions are free of data races.
  • If a program is correctly synchronized, then all executions of the program will appear to be sequentially consistent (§17.4.3).
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM