Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added some volatile vs synchronization performance advice

...

In the previous example, statement 4 also sees the statements 1 and 2 to have executed and all their operands with the most-up to date values. However, this does not mean that statements 1 and 2 are sequentially consistent with respect to each other. They may be freely reordered by the compiler. In fact, if statement 1 constituted a read of some variable x, it could see the value of a future write to x in statement 2.

Wiki Markup
Because the guarantees of code present before the {{volatile}} write are weaker than sequentially consistent code, {{volatile}} as a synchronization primitive, performs better. "Because no locking is involved, declaring fields as {{volatile}} is likely to be cheaper than using synchronization, or at least no more expensive. However, if {{volatile}} fields are accessed frequently inside methods, their use is likely to lead to slower performance than would locking the entire methods." \[[Lea 00|AA. Java References#Lea 00]\].

Wiki Markup
"Finally, note that the actual execution order of instructions and memory accesses can be in any order as long as the actions of the thread appear to that thread as if program order were followed, and provided all values read are allowed for by the memory model. This allows the programmer to fully understand the semantics of the programs they write, and it allows compiler writers and virtual machine implementors to perform complex optimizations that a simpler memory model would not permit." \[[JPL 06|AA. Java References#JPL 06]\]. 

...