CodeBlanks Logo Icon CodeBlanks

happens-before

Learn memory ordering with happens-before.

The happens-before relation

happens-before is the ordering guarantee of the Java Memory Model (JMM). If action A happens-before B, then the memory effects of A are visible to B. This gives consistency between threads.

Several mechanisms establish it: a synchronized block makes the changes of the thread releasing the lock visible to the one acquiring it; a volatile write is seen by later reads; final fields become visible when the constructor finishes. Without happens-before a thread may never see another's write.

Ordering with synchronized

A synchronized block or method forces all threads using the same lock to enter one at a time. All changes made by the thread releasing the lock become visible to the next thread acquiring it.

Example: in a Counter class with synchronized void inc() and synchronized int get(), when a thread calls inc and releases the lock, a later thread calling get sees the new value. This is the most concrete form of the happens-before relation.

Practice Synchronized counter

Write a Counter class with a private int count field, synchronized void inc() and synchronized int get() methods. inc does count++. In main, call inc twice and print the get result with System.out.println.

Starter code

Main.java
// Define the Counter class
// Add synchronized inc and get
// Print the result in main

Sample solution

Main.java
class Counter {
    private int count;
    public synchronized void inc() { count++; }
    public synchronized int get() { return count; }
}

public class HappensBeforeDemo {
    public static void main(String[] args) {
        Counter c = new Counter();
        c.inc();
        c.inc();
        System.out.println(c.get());
    }
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the guarantee mechanisms

Term Meaning
synchronized Happens-before
volatile Visibility
final Safe publication
local variable Single thread

2 Which mechanism establishes the happens-before relation?

  • synchronized block Correct answer
  • local variable
  • final field
  • Metaspace

Explanation: synchronized establishes happens-before with a lock.

3 Add the synchronized keyword

Question
public ____ void inc() { count++; }
Answer
public synchronized void inc() { count++; }

Explanation: synchronized locks and orders the method.

All lessons in Expert