Java
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.
Exercise 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.
Show example solution
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);
}
}
Exercise 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.
Show example solution
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);
}
}
Test yourself
-
Which keyword provides memory visibility?
Show answer
volatile — volatile guarantees a field's visibility.
-
Declare a volatile flag
private ____ boolean active;
Show answer
private volatile boolean active;
Next lesson: Buffer