Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Java happens-before relation, clarification needed

It is said in JLS:

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.

also there is said:

Writes in one thread that are in a data race with reads in another thread may, for example, appear to occur out of order to those reads.

Does this mean that if hb(r, w), then r must be prior to w, or that if r is before, then happens-before relation takes place?

like image 955
dhblah Avatar asked Mar 25 '26 18:03

dhblah


1 Answers

hb(r, w) means that r is executed before w AND w can see the result of r.

In the case of read / write actions, you generally care about having a hb(w, r) and want to make sure that the read sees the result of the write.

Example using a synchronized block:

Block w (writes):

synchronized (lock) { //lock is a final object
    aVariable = something;
}

Block r (reads):

synchronized (lock) { //the same final object
    System.out.println(aVariable)
}

w and r are synchronized on the same monitor, so there is a happens-before relationship between the 2.

Let's say that w is executed before r, meaning that we have hb(w, r), then the JMM guarantees that r will print the latest value of aVariable.

Without the synchronized blocks, there is no happens-before relationship any more and even if w is executed before r (from a wall clock perspective), r might print a stale value of aVariable.

Without a happens-before relationship, it might even be the case that w is executed after r even if your program is written in a way that it should not be the case (i.e. the JVM might have reordered the operations).

A very good example of how weird things can get without a happens-before relationship is given in the JLS - Example 17.4-1.

like image 54
assylias Avatar answered Mar 28 '26 06:03

assylias