CodeBlanks Logo Icon CodeBlanks

Summary - Memory model

Combine happens-before and volatile to write a publish utility.

Summary - Memory model

In this group we saw the foundations of the Java Memory Model: the stack and heap split, happens-before ordering, visibility with volatile, safe publication with final fields, and Metaspace. These give consistency between threads.

For thread safety remember three keywords: synchronized for ordering and mutual exclusion, volatile for visibility, final for immutability and safe publication. Now we review them with two small tasks.

Using them together

In real systems these keywords are used together. final for immutable state, volatile for a simple flag, synchronized for complex read-modify-write operations.

Example: in a Config class the name is immutable so final String name, the active flag can change so volatile boolean active. This combination gives both safe publication and up-to-date visibility. Picking the right keyword avoids needless locking and keeps performance.

Practice final and volatile in the Config class

Write a Config class with final String name and volatile boolean active fields; a Config(String name) constructor assigns name and sets active = true. In main, create new Config("app") and print the c.name value with System.out.println.

Starter code

Main.java
// Define the Config class
// Add final name and volatile active
// Print the name in main

Sample solution

Main.java
class Config {
    final String name;
    volatile boolean active;
    public Config(String name) { this.name = name; this.active = true; }
}

public class ConfigDemo {
    public static void main(String[] args) {
        Config c = new Config("app");
        System.out.println(c.name);
    }
}

Expected output

app

Practice An immutable Triangle class

Define a Triangle class with final int a, final int b, final int c fields and a constructor that assigns them. In main, create new Triangle(2, 3, 4) and print t.a + t.b + t.c with System.out.println.

Starter code

Main.java
// Define the Triangle class
// Add final a, b, c fields
// Print the sum in main

Sample solution

Main.java
class Triangle {
    final int a;
    final int b;
    final int c;
    public Triangle(int a, int b, int c) { this.a = a; this.b = b; this.c = c; }
}

public class TriangleDemo {
    public static void main(String[] args) {
        Triangle t = new Triangle(2, 3, 4);
        System.out.println(t.a + t.b + t.c);
    }
}

Expected output

9

Questions and answers

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

1 Which keyword provides memory visibility?

  • volatile Correct answer
  • new
  • getClass
  • int

Explanation: volatile guarantees a field's visibility.

2 Declare a volatile flag

Question
private ____ boolean active;
Answer
private volatile boolean active;

Explanation: A volatile flag guarantees visibility.

All lessons in Expert