title: Java volatile and cache coherency. Am I missing something?
body: <p>In numerous articles, YouTube videos, etc., I have seen Java's <code>volatile</code> keyword explained as a problem of cache memory, where declaring a variable <code>volatile</code> ensures that reads/writes are forced to main memory, and not cache memory.</p>
  <p>It has always been my understanding that in modern CPUs, cache memory implements coherency protocols that guarantee that reads/writes are seen equally by all processors, cores, hardware threads, etc, at all levels of the cache architecture. Am I wrong?</p>
  <p><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.1.4" rel="nofollow noreferrer">jls-8.3.1.4</a> simply states</p>
  <blockquote>
  <p>A field may be declared <code>volatile</code>, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).</p>
  </blockquote>
  <p>It says nothing about caching. As long as cache coherency is in effect, <code>volatile</code> variables simply need to be written to a memory address, as opposed to being stored locally in a CPU register, for example. There may also be other optimizations that need to be avoided to guarantee the contract of <code>volatile</code> variables, and thread visibility.</p>
  <p>I am simply amazed at the number of people who imply that CPUs do not implement cache coherency, such that I have been forced to go to StackOverflow because I am doubting my sanity. These people go to a great deal of effort, with diagrams, animated diagrams, etc. to imply that cache memory is not coherent.</p>
  <p>jls-8.3.1.4 really is all that needs to be said, but if people are going to explain things in more depth, wouldn't it make more sense to talk about CPU Registers (and other optimizations) than blame CPU Cache Memory?</p>