Visibility, atomicity and ordering
Definition:
Happens-before orders actions so earlier writes become visible to an observing thread.
Explanation:
Using the same volatile variable creates a happens-before edge from the publishing write to a subsequent reader of that value.
Illustration image:
Example:
class Mailbox {
private String message;
private volatile boolean ready;
void send(String value) { message = value; ready = true; }
String poll() { return ready ? message : null; }
}Expected behavior. This is a one-shot publication illustration. Resetting it or introducing several writers needs a new concurrency protocol.
Internal working:
Actions before publication become visible through the transitive relationship. A plain polling flag has a data race. A volatile count increment remains a compound read–modify–write, so visibility does not prevent lost updates.
Interview questions:
Why does a volatile flag publish preceding writes but not make count++ atomic?
Publication supplies a visibility edge. Increment still needs an indivisible read–modify–write.