When mentioning memory in Java, many people will think of JVM. The memory model discussed in this article will also be misunderstood as this. In fact, this is also a test point that is more likely to make mistakes in the interview. The abbreviation of the memory model is jmm. I believe it will not be easily confused if it is displayed in English names. Below we will explain the concept of Java memory model and help you distinguish it from jvm.
1. Concept
Java Memory Model (Java Main Memory, JMM for short) is an abstract concept and has many similarities with the computer memory model. JMM mainly includes threads, working memory, and main memory to interact. The working memory can be compared to the cache of calculation, but the working memory between threads is independent of each other; the main memory is similar to the main memory of the computer, and the variable value transfer between threads is mainly This is done through main memory. At the same time, JMM also has instruction reordering to optimize the order of code execution. Simply put, the order in which the code is written is not necessarily the order in which the code is executed.
2. The difference between JMM and JVM
The Java memory model looks similar to the Java memory structure (JVM memory structure). Many people mistakenly think that the two are the same thing, which often leads to incorrect answers during the interview process.
The Java heap and method area are data areas shared by multiple threads. In other words, multiple threads may be able to operate on the same data stored in the heap or method area. This is what we often call "Java threads communicate through shared memory."
The Java memory model is translated from the English Java Memory Model (JMM). In fact, JMM does not exist as real as the JVM memory structure. It's just an abstract concept. JSR-133: Java Memory Model and Thread Specification describes that JMM is related to multi-threading. It describes a set of rules or specifications. This specification defines that when one thread writes to a shared variable, it is visible to another thread. of.
So, to briefly summarize, Java's multi-threads communicate through shared memory, and due to the use of shared memory for communication, there will be a series of problems such as visibility, atomicity, order, etc. during the communication process, and JMM It is a model built around multi-threaded communication and a series of features related to it. JMM defines some syntax sets, which are mapped to keywords such as volatile and synchronized in the Java language.
The above is an introduction to the memory model in Java. This article focuses on sharing the basic theory. You can focus on distinguishing jmm and jvm, and you can be more clear about these two concepts when studying in the future .