The Java memory model question 17 of 180 senior
What is safe publication, and which ways of achieving it can you name?
- Making every field private
- Correct: Publishing a reference so that the writes made during construction are guaranteed visible to whoever reads it
- Copying the object before sharing it
- Calling
System.gc()after construction
Publishing an object means making a reference reachable by another thread. Unsafely published, the reader may see the reference before the fields, and observe a half-built object even though the code never mutates it after construction.
The safe ways, all of which come down to a happens-before edge between the construction and the read:
- Initialise it from a static initialiser.
- Store the reference into a
volatilefield or anAtomicReference. - Store it into a
finalfield of a properly constructed object. - Guard it with a lock, written and read under the same lock.
- Hand it over through a thread-safe collection, a
BlockingQueue, or an executor task.
An immutable object with all-final fields is the exception that needs none of this: the final-field guarantee makes it safe to share by any means, including a data race.