Sobes.tech
Middle+

What is safe publication?

sobes.tech AI

Answer from AI

Safe publication is a guaranteed way of sharing an object's state between threads. If an object is safely published, every thread that can see the reference to this object is guaranteed to see its state at the moment of publication.

Problems without safe publication:

  • Inconsistent state: A thread may see a partial or outdated state of the object if its constructor has not finished or changes have not been fully propagated to main memory.
  • Visibility: Changes made by one thread may be invisible to other threads.

Ways to ensure safe publication:

  1. Initialization of static fields: An object assigned to a static field during class initialization is safely published.
    // The 'instance' object is safely published
    public static final MyClass instance = new MyClass();
    
  2. Volatile fields: Assigning a reference to an object to a volatile field guarantees visibility of the reference and the object's state at the moment of assignment.
    // The 'obj' object is safely published after assignment
    private volatile MyObject obj;
    
    public void publish(MyObject newObj) {
        this.obj = newObj;
    }
    
  3. Final fields: An object assigned to a final field in the constructor is safely published after the constructor completes.
    // The 'data' object is safely published after constructor completion
    private final Data data;
    
    public MyClass(Data data) {
        this.data = data; // assignment to final field
    }
    
    Important: The reference to this should not "leak" from the constructor before its completion, until final fields are initialized.
  4. Using synchronization or concurrent collections: Publishing through thread-safe mechanisms (synchronized, Lock, ConcurrentHashMap, etc.).
    // The 'sharedObject' is safely published via synchronized block
    private Object sharedObject;
    private final Object lock = new Object();
    
    public void publish(Object obj) {
        synchronized (lock) {
            this.sharedObject = obj;
        }
    }
    
    public Object getSharedObject() {
        synchronized (lock) {
            return this.sharedObject;
        }
    }
    
  5. Placing objects in concurrent collections: Objects placed in thread-safe collections (e.g., ConcurrentHashMap, CopyOnWriteArrayList) are safely published.
    // Objects placed in a map are safely published
    private final ConcurrentMap<String, MyObject> map = new ConcurrentHashMap<>();
    
    public void addObject(String key, MyObject value) {
        map.put(key, value);
    }
    

Safe publication is a fundamental requirement for writing correct multithreaded code in Java, preventing visibility and inconsistent state issues.

What is safe publication? — Java - sobes.tech