# Happened-before

In computer science, the happened-before relation (denoted: ${\displaystyle \to \;}$) is a relation between the result of two events, such that if one event should happen before another event, the result must reflect that, even if those events are in reality executed out of order (usually to optimize program flow). This involves ordering events based on the potential causal relationship of pairs of events in a concurrent system, especially asynchronous distributed systems. It was formulated by Leslie Lamport.[1] In Java specifically, a happens-before relationship is a guarantee that memory written to by statement A is visible to statement B, that is, that statement A completes its write before statement B starts its read.[1]

The happened-before relation is formally defined as the least strict partial order on events such that:

• If events ${\displaystyle a\;}$ and ${\displaystyle b\;}$ occur on the same process, ${\displaystyle a\to b\;}$ if the occurrence of event ${\displaystyle a\;}$ preceded the occurrence of event ${\displaystyle b\;}$.
• If event ${\displaystyle a\;}$ is the sending of a message and event ${\displaystyle b\;}$ is the reception of the message sent in event ${\displaystyle a\;}$, ${\displaystyle a\to b\;}$.

If there are other causal relationships between events in a given system, such as between the creation of a process and its first event, these relationships are also added to the definition.

Like all strict partial orders, the happened-before relation is transitive, irreflexive and antisymmetric, i.e.:

• ${\displaystyle \forall a,b,c}$, if ${\displaystyle a\to b\;}$ and ${\displaystyle b\to c\;}$, then ${\displaystyle a\to c\;}$ (transitivity). This means that for any three events ${\displaystyle a,b,c}$, if ${\displaystyle a}$ happened before ${\displaystyle b}$, and ${\displaystyle b}$ happened before ${\displaystyle c}$, then ${\displaystyle a}$ must have happened before ${\displaystyle c}$.
• ${\displaystyle \forall a,a\nrightarrow a}$ (irreflexivity). This means that no event can happen before itself.
• ${\displaystyle \forall a,b,}$ where ${\displaystyle a\neq b}$, if ${\displaystyle a\to b}$ then ${\displaystyle b\nrightarrow a}$ (antisymmetry). This means that for any two distinct events ${\displaystyle a,b}$, if ${\displaystyle a}$ happened before ${\displaystyle b}$ then ${\displaystyle b}$ cannot have happened before ${\displaystyle a}$.

The processes that make up a distributed system have no knowledge of the happened-before relation unless they use a logical clock, like a Lamport clock or a vector clock. This allows one to design algorithms for mutual exclusion, and tasks like debugging or optimising distributed systems.