18

If cache coherency is implemented at hardware level why do we need volatile? Any core/processor should get the latest value anyway?

Or is it dealing with a different issue completely?

leppie
  • 115,091
  • 17
  • 196
  • 297
sab
  • 9,767
  • 13
  • 44
  • 51
  • 1
    You may want to read [this question](http://stackoverflow.com/questions/2441279/volatile-guarantees-and-out-of-order-execution), or the Java Language Specification, where this is explained. – vanza Jan 15 '14 at 04:23
  • @vanza the question you provided does not refer to the **cache coherency** keyword – choxsword Nov 25 '19 at 12:11

1 Answers1

13

Cache coherence may be implemented at the processor level but, unless the processor memory model guarantees sequential consistency (which is not the case on most modern architectures), you will only get cache coherence if you ask for it.

That is what volatile is for: it asks the JVM to produce the relevant machine instruction(s) that will ask the processor(s) to synchronize its cache with main memory.

assylias
  • 321,522
  • 82
  • 660
  • 783