Memory model · Topic 4 of 5
Safe publication and final fields
Definition​
Safe publication means handing an object to other threads so they see it fully built. Objects whose fields are final are safe to share even through a plain field, because Java guarantees other threads see the final fields set by the constructor.
Example code​
An immutable object shared between threads
class Settings {
final String host; // final fields are visible once the constructor finishes
final int port;
Settings(String host, int port) {
this.host = host;
this.port = port;
}
}
class Demo {
static Settings current; // shared between threads without a lock
public static void main(String[] args) throws InterruptedException {
Thread publisher = new Thread(() -> current = new Settings("localhost", 8080));
publisher.start();
publisher.join();
// a reader can never see a half-built Settings with a null host or port 0
System.out.println(current.host + ":" + current.port);
}
}
// Output:
// localhost:8080
Finished this page? Track your progress (saved only in your browser).