The memory model of Java

Source: Internet
Author: User

Java memory model

The Java Virtual Machine specification attempts to define a Java memory model (MODEL,JMM) that masks the access differences of various hardware and operating systems to allow Java programs to achieve consistent memory access across various platforms. Prior to this, mainstream programming languages (such as C + +, etc.) directly use the physical hardware and operating system's memory model, therefore, due to differences in memory models on different platforms, it is possible to cause the program to be completely normal on a set of platforms, while concurrent access on another set of platforms is often error- Therefore, it is not allowed to write programs for different platforms under certain scenarios. The Java memory model needs to be sufficiently rigorous to make Java's concurrent memory access operations ambiguous, and the Java memory model must be loosely defined enough to allow the virtual machine's implementation to have enough free space to take advantage of the various features of the hardware to get better execution speed. After a long period of validation and patching, JDK1.5 (implemented JSR-133) was released, the Java memory model has matured and perfected, together to look at.

Main memory and working memory

The main purpose of the Java memory model is to define the access rules for each variable in the program, that is, the underlying details of storing variables in the virtual machine into memory and removing variables from memory. Note that the variables here do not include local variables and method parameters, because they are thread-private, are not shared, and naturally there is no competition, and the variables here should be instance fields, static fields, and elements that make up the array object.

The Java memory model specifies that all variables are stored in the main memory (main memories), that each thread has its own working memory (working memories), that the thread's working memory holds the variables that are used by the thread and the copy of the Master memory (note This will never be a copy of the entire object, imagine a 10M object that has a 10M copy in each working memory used by this object, and memory is still available? that is, the fields in the objects used in the thread), all the operations (reads, assigns) of the variables must be done in working memory, and not directly read and write to the variables in main memory. There is no direct access to variables in the other's working memory between different threads, and the transfer of variable values between threads needs to be done through main memory , and the interaction between threads, main memory, and working memory.

Inter-memory interaction

With regard to the specific interaction protocol between main and working memory, i.e. how a variable is copied from the main memory to the working memory, how to synchronize from the working memory back to the main memory, the following 8 operations are defined in the Java memory model, and the virtual machine implementation must ensure that each operation of the following volume is atomic, Not to be divided:

1. Lock (Lock): A variable acting on the main memory, which identifies a variable as a thread-exclusive state

2. Unlock (Unlocked): A variable that acts on the main memory, releasing a variable that is in a locked state, and the released variable can be locked by another thread

3. READ: A variable acting on the main memory that transfers the value of a variable from main memory to the working memory of the thread for subsequent load actions to use

4. Load (load): A variable that acts on the working memory, which puts the value of a read operation from the main memory into a variable copy of the working memory

5, use: The variable that acts on the working memory, it passes the value of a variable in the working memory to the execution engine, and does this when the virtual opportunity is to a bytecode instruction that needs to use the value of the variable.

6. Assign (Assignment): A variable in the working memory that assigns a value received from the execution engine to a variable in the working memory, which is performed whenever the virtual opportunity is assigned to a byte-code instruction that assigns a value to a variable.

7. Store: A variable in working memory that transfers the value of a variable in the working memory to main memory for subsequent write operations to use

8. Write (write): A variable that acts on the main memory, which puts the store operation from the value of the variable in the working memory into the variable of the main memory

The Java memory model also specifies that the following rules must be met when performing the 8 basic operations described above:

1. One of the read and load, store, and write operations is not allowed to appear separately

2, does not allow a thread to discard its most recent assign operation, that is, the variable in the working memory changes the lag must synchronize the change back to the main memory

3. One thread is not allowed to synchronize data from the working memory of the thread back to main memory for no reason

4, a new variable can only be born from the main memory, not allowed in working memory directly using a non-initialized (load or assign) variable

5. A variable is allowed only one thread to lock it at the same time, but the lock operation can be repeated multiple times by the same thread, and after executing lock multiple times, the variable will be unlocked only if the same number of unlock operations are performed .

6. If you perform a lock operation on the same variable, it will empty the value of this variable in the working memory and need to re-execute the value of the load or assign operation initialization variable before the execution engine uses the variable .

7, if a variable is not locked by the lock operation beforehand, it is not allowed to unlock operation, nor allow to unlock a variable locked by another thread

8. before performing a unlock operation on a variable, you must first synchronize this variable back into main memory

Atomicity, Visibility, ordering

The Java memory model is built around the three characteristics of how atomicity, visibility, and ordering are handled in the concurrency process, to look at it one at a glance:

1. atomicity (atomicity)

The Java memory model directly guarantees the operation of atomic variables including read, load, assign, use, store, write, which can roughly be considered to be atomic in the basic data type of access reading and writing. If the scenario requires a greater atomicity guarantee, the Java memory model also provides lock and unlock, although the virtual machine does not open the lock and unlock operations directly to the user, But it provides a higher level bytecode directive Monitorenter and monitorexit to implicitly use these two operations, these two bytecode instructions are reflected in Java code is the synchronization block----synchronized keyword

2. Visibility (Visibility)

Visibility means that when a thread modifies the value of a shared variable, other threads can immediately know the change. Volatile has actually written this point in detail, in fact, the Synchronized keyword is also possible to achieve visibility, the visibility of synchronized is "to perform a unlock operation on a variable, you must first synchronize this variable back to the main memory" this rule obtained. In addition, the final keyword can also achieve visibility, because the final modified field will be visible in the constructor once the initialization is complete and the constructor does not pass this out, and the value of the final field can be seen in other threads.

3, order (ordering)

The natural ordering of Java programs can be summed up in one sentence: If you observe in this thread, all operations are orderly, and if you look at another thread in a thread, all operations are unnecessary . The first half of the sentence refers to the "line range expression as the semantics of walking," the latter sentence refers to "order reordering" and "working memory and main memory synchronization delay" phenomenon. The Java language provides the volatile and synchronized two keywords to ensure the ordering of operations between threads, and the volatile keyword itself contains the semantics of prohibiting command reordering, while synchronized is the " A variable that allows only one thread to lock on it at the same time "this rule provides that the two synchronized blocks holding the same lock can only be entered in a serial line

First occurrence Happens-before principle

If all the ordering in the Java memory model is done only by volatile and synchronized, then some of the operations will become cumbersome, but we do not feel this when writing Java code, because there is one in the Java language " First occurrence (Happens-before) "principle. This principle is very important, it is to judge whether the data is competitive, thread is the main basis for security, relying on this principle, we can use a few rules to determine whether there are two operations in the concurrency between the possible conflict between the problem.

The so-called antecedent principle refers to the partial order relationship between two operations defined in the Java memory model, and if operation a precedes operation B, the effect of operation A can be observed by Operation B, which includes modifying the values of shared variables in memory, sending messages, calling methods, and so on. Java memory model has some natural, do not need any synchronization aids in the pre-existing relationship:

1, program Order rules: In a thread, according to the control flow sequence, control flow in front of the operation first occurs in the control flow behind the operation, said "control flow" because also to consider the branch, loop structure

2, the Tube lock rule: A unlock operation first occurs after the face of the same lock operation lock

3. Volatile variable rules: The write operation of a volatile variable takes precedence over the read operation of the variable after facing it

4. Thread Start rule: the Start () method of the thread object takes precedence over each action of this thread

5. Thread termination rule: All operations in the thread first occur on termination detection of this thread

6. Thread break rule: the invocation of the thread interrupt () method occurs when the code of the interrupted thread detects that the interrupt event occurred

7. Object termination rule: Initialization of an object occurs at the beginning of its finalize () method

8, the principle of transitivity: If the operation a first occurs in operation B, Operation B first occurs in Operation C, then operation a must first occur in Operation C

The Java language does not need any synchronous means to ensure that the first occurrence of the rules can be established only above these amounts, if the relationship between the two is not, and can not be deduced by the following rules, they do not have the order of protection. Take an example to see:

Private int i = 0;  Public void SetI (int  i) {    this. i = i;}   Public int Geti () {    return  i;}

A very common set of getter/setter, assuming that a line enters upgradeable calls SETI (1), and the B thread calls the same object's Geti (), what is the return value of the B thread?

The rules of the first occurrence principle are analyzed in turn. Since two methods are called separately by two threads, the rules of Procedure order do not apply here, and because there is no synchronization block, there is no unlock and lock, so the pipe lock rule does not apply here; I is not modified by the keyword volatile, so the volatile variable rule does not apply here , the subsequent start, end, interrupt, and object termination are not related to this, and therefore do not apply. Because there is not a practical first occurrence rule, so the last transfer is not discussed, so transitivity also does not apply. Since all the antecedent principles do not apply, even though the SETI (1) operation of thread A first occurs in time, it is not possible to determine the return result of thread B's Geti (), in other words, the operation is not thread safe.

So how do you fix this problem? There are at least two simple ways to do this:

1, setter/getter are defined as synchronized, so you can apply enhancement locking rules

2, I is defined as a volatile variable, because the setter method changes to I do not depend on the original value of I, to meet the volatile keyword usage scenario, so you can apply the volatile variable rule

The memory model of Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.