Happens-before relationships

suggest change

(The following is a simplified version of what the Java Language Specification says. For a deeper understanding, you need to read the specification itself.)

Happens-before relationships are the part of the Memory Model that allow us to understand and reason about memory visibility. As the JLS says (JLS 17.4.5):

“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.”

What does this mean?

Actions

The actions that the above quote refers to are specified in JLS 17.4.2. There are 5 kinds of action listed defined by the spec:

- Volatile read: Reading a volatile variable.

- Volatile write: Writing a volatile variable.

- Lock. Locking a monitor

- Unlock. Unlocking a monitor.

- The (synthetic) first and last actions of a thread.

- Actions that start a thread or detect that a thread has terminated.

Program Order and Synchronization Order

These two orderings ( JLS 17.4.3 and JLS 17.4.4 ) govern the execution of statements in a Java

Program order describes the order of statement execution within a single thread.

Synchronization order describes the order of statement execution for two statements connected by a synchronization:

Happens-before Order

This ordering ( JLS 17.4.5 ) is what determines whether a memory write is guaranteed to be visible to a subsequent memory read.

More specifically, a read of a variable v is guaranteed to observe a write to v if and only if write(v) happens-before read(v) AND there is no intervening write to v. If there are intervening writes, then the read(v) may see the results of them rather than the earlier one.

The rules that define the happens-before ordering are as follows:

In addition, various classes in the Java standard libraries are specified as defining happens-before relationships. You can interpret this as meaning that it happens somehow, without needing to know exactly how the guarantee is going to be met.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Java Memory Model:
* Happens-before relationships

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
130 Java Memory Model
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap