Java Memory Model
From Wikipedia, the free encyclopedia
The Java programming language and platform provide thread capabilities. Thread synchronization is notoriously difficult for developers, and the problem is magnified because a Java application could run on a wide range of processors or operating systems. The Java Memory Model (JMM) defines execution-time constraints on the relationship between threads and main memory in order to achieve consistent and reliable Java applications.
In a single-threaded environment, it is easy to reason about code execution, because the Java Language Specification requires a Java Virtual Machine to implement as-if-serial semantics. Difficulties arise in a multithreaded environment, especially where shared-memory multiprocessor hardware is concerned. The JMM makes it possible to reason about code execution in a multithreaded environment, even in the face of optimizations performed by the dynamic compiler, the processor(s) and the caches.
[edit] Code Execution in a Multithreaded Environment
Compliant JVM implementations are required to observe within-thread as-if-serial semantics. The runtime (and specifically, the dynamic compiler) is free to introduce any useful execution optimizations so long as the result is guaranteed to be exactly the same it would have been had all the statements been executed in program order.
In a multithreaded environment the situation is quite different. As-if-serial semantics do not prevent different threads from having different views of the data. Each thread has its own working memory whose contents may or may not be in sync with the contents of the shared main memory; moreover, in multiprocessor architectures, individual processors may have their own local caches that are out of sync with main memory. It is generally undesirable to require threads to remain perfectly in sync with one another because this would be too costly from a performance point of view. Unfortunately, this means that at any given time, different threads may see different values for the same shared data.
The JMM is essentially a set of rules that specify the conditions under which one may safely assume that threads have a synchronized view of the data.
[edit] External links
- Java theory and practice: Fixing the Java Memory Model, part 1 - An article describing problems with the original Java memory model.
- Java theory and practice: Fixing the Java Memory Model, part 2 - Explains the changes JSR 133 made to the Java memory model.