Oracle's documentation on atomic access (at http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html) says this:
"a volatile variable establishes a happens-before relationship... . This means that ... when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change."
I'm having trouble wrapping my head around that. I understand how volatile variables work (in >= Java 5), but I'm wondering how the java decides what side-affect "led up" to the change of a volatile variable.
So I guess my question is: What side-effects are given this guarantee?
EDIT:
So I've learned that if thread A modifies a volatile variable, and then thread B reads it, all writes from thread A that happened before the write to the volatile variable are "made coherent" with respect to thread B (ie the cached values of variables subject to the afore mentioned writes by thread A are invalidated in thread B). Correct me if I'm wrong.
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.
"Volatile" simply ensures that whenever a reference to the variable is done (either read or write), JVM performs a reference to the assigned address of the variable in virtual memory space, rather than to a value stored in a register or in some other convenient shadow location (such as stack) selected by the optimizer, ...
The volatile keyword flushes the changes directly to the main memory instead of the CPU cache. On the other hand, the transient keyword is used during serialization. Fields that are marked as transient can not be part of the serialization and deserialization.
Most multiprocessor caches have coherency mechanisms, so the penalty isn't as bad as flushing all the caches.
Any writes in the thread that wrote to the volatile before doing so will be seen by the thread reading the volatile after having done so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With