The Java Memory Model
While we were never explicit about it throughout this chapter, we have actually defined most of the JMM. What is a memory model in the first place?
A language memory model is a specification that describes the circumstances under which a write to a variable becomes visible to other threads. You might think that a write to a variable v
changes the corresponding memory location immediately after the processor executes it, and that other processors see the new value of v
instantaneously. This memory consistency model is called sequential consistency.
As we already saw in the ThreadSharedStateAccessReordering
example, sequential consistency has little to do with how processors and compilers really work. Writes rarely end up in the main memory immediately; instead, processors have hierarchies of caches that ensure a better performance and guarantee that the data is only eventually written to the main memory. Compilers are allowed to use registers to postpone or avoid...