Some of the problems that may arise in the memory model and concurrent programming are discussed earlier. Let's take a look at the Java memory model,
Look at what guarantees the Java memory model provides for us and what methods and mechanisms are available in Java to ensure the correctness of program execution in the case of multithreaded programming.
In the Java Virtual Machine specification, an attempt was made to define a Java memory model (MODEL,JMM) to mask the memory access differences of each hardware platform and operating system.
To enable Java programs to achieve consistent memory access across a variety of platforms. So what does the Java memory model prescribe, which defines the access rules for variables in the program,
To a larger extent, it defines the order in which the program executes. Note that in order to achieve better execution performance,
The Java memory model does not limit the execution engine's use of processor registers or caches to improve instruction execution speed.
There is also no restriction on the compiler to reorder instructions. In other words, in the Java memory model, there is also the problem of cache consistency and instruction reordering.
The Java memory model stipulates that all variables are present in main memory (similar to the physical memory mentioned earlier), and each thread has its own working memory (similar to the previous cache).
All the operations of a thread on a variable must be done in working memory, not directly on main storage. And each thread cannot access the working memory of other threads.
To give a simple example: in Java, execute the following statement:
I = 10;
The execution thread must first assign a value to the cache row where the variable I resides in its own worker thread before writing to the host. Instead of writing the value 10 directly into main memory.
2.3.1 Java memory model