Three, java multithreading basis of java memory model (JMM)

First, the three characteristics multithreading

1. Atomicity: i.e. one or more operations or all operations performed and the process will not be interrupted execution of any factor, or it is not performed.

A classic example is the bank account transfer problem:
for example, transfer from account A to account B 1000 yuan, it must include two operations: minus 1000 yuan from account A, B to account plus 1,000 yuan. These two operations must have the atomicity to ensure that there is some unexpected problems.

We also true operational data, such as i = i + 1; including the read value of i, i is calculated, written i. This line of code in Java is not available atomic, then there will be problems running multi-threaded, so we also need to use synchronization and lock these things to make sure that this feature of.

In fact, atomicity is to ensure data consistency, security thread part,

2. Visibility: When multiple threads access the same variable, a thread changes the value of this variable, other threads can immediately see the modified values. If two threads in different cpu, then thread 1 changes the value of i did not modify the thread to refresh main memory, thread 2 and i use, it is still before the affirmation of the value of i, the thread 1 of the variables did not see this is the visibility of the problem.

3. ordering: the program execution sequence performed in the order code. In general processor in order to improve process efficiency, might enter the code optimization, it does not ensure the implementation of the program in individual statements in the order consistent with the order of the code, but it will ensure that the final program execution and results of the code sequence the result is the same. as follows:

int a = 10; // statement 1

int r = 2; // statement 2

a = a + 3; // statement 3

r = a * a; // statement 4

Because the reordering, he might order of execution is 2-1-3-4,1-3-2-4
but not likely 2-1-4-3, because it breaks the dependency.
Obviously reorder single thread is not going to have any problems, but not necessarily multi-threaded, so we have to consider this issue at the time of multi-threaded programming.

Two, java memory model

1. shared memory model refers to the Java Memory Model (referred JMM), JMM decided to write one thread to shared variables, it can be seen on another thread. From an abstract point of view, JMM defines an abstract relationship between the thread and the main memory: the main memory (main memory), each thread has a private local memory (local memory) shared among threads variable storage , local memory stored a copy of the thread to read / write shared variables. JMM local memory is an abstract concept, and are not real. It covers the cache, write buffer, registers and other hardware and compiler optimizations.

2. Picture

From the map view, between threads A and B are as threads to be communicated, it must go through the following two steps:

2.1. First, the updated thread A local memory A shared variables to be flushed to main memory.

2.2. Then, the thread B reads to main memory before the thread A has updated the shared variable.

3. These two steps will be described below by schematic:

3.1. As shown above, A and B have local memory in the main memory copy of the shared variable x. Assuming initial, x values ​​of these three memory are 0. A thread, when executed, updates the value of x (assuming a value of 1) temporarily stored in its own local memory in A. When thread A and thread B requires communication, the thread A first value of x will own flushed to main memory after the local memory modification, the value of x at this time the main memory becomes the 1. Subsequently, the thread B to the main memory to read the value of x after the update thread A, the value of x at this time the local memory of the thread B also becomes 1.

Overall, these two steps substantially in the thread A thread sends a message to B, and the communication process must go through main memory. JMM by controlling the interaction between the main memory and the local memory of each thread, to provide visibility of memory guarantee java programmer.

4. Summary

What is J AVA memory model: the Java memory model referred to as the JMM , set defines a thread to another visible thread. Shared variables stored in the main memory, each thread has its own local memory, as when multiple threads access a data might not timely refresh local memory to the main memory, so the thread will happen security issues.

Third, what is volatile

After the value of 1. In other words, once the visibility of a thread modifies the modified variable is volatile, it will ensure that the modified values ​​are immediately updated to the main memory, when there are other threads need to read, you can obtain immediately amend .

2. In Java in order to speed up the efficiency of the program, the operation of some of the variables is usually performed on the thread registers or CPU cache, only after synchronized to the main memory, and add the volatile modifier is variable It is directly read and write main memory.

3.Volatile ensure the timely visibility of variables shared between threads, but can not guarantee atomicity.

class ThreadVolatileDemo extends Thread {
    public  volatile  boolean flag = true;
    @Override
    public void run() {
        System.out.println("开始执行子线程....");
        while (flag) {
        }
        System.out.println("线程停止");
    }
    public void setRuning(boolean flag) {
        this.flag = flag;
    }
}
public class ThreadVolatile {
    public static void main(String[] args) throws InterruptedException {
        ThreadVolatileDemo threadVolatileDemo = new ThreadVolatileDemo();
        threadVolatileDemo.start();
        Thread.sleep(3000);
        threadVolatileDemo.setRuning(false);
        System.out.println("flag 已经设置成false");
        Thread.sleep(1000);
        System.out.println(threadVolatileDemo.flag);
    }
}

4. Results

4.1. The results (plus volatile)

开始执行子线程....
flag 已经设置成false
线程停止
false开始执行子线程....
flag 已经设置成false
线程停止
false

4.2 The results (without volatile, the result has also been set fasle Why run it?. Reason: between the thread is not visible, read a copy, there is no time to read the results of a solution to the main memory to use. when Volatile keyword will solve visibility between threads, each thread is forced to read the value of all the "main memory" value )

开始执行子线程....
flag 已经设置成false
false

Four, Volatile and Synchronized difference

1. so that we can see that although having atomic volatile but does not guarantee visibility.

2. Performance, synchronized keyword to prevent multiple threads to execute a piece of code, it will affect the efficiency of program execution, and the volatile keyword in some cases better performance than synchronized.

3. But be careful volatile keyword is no substitute for the synchronized keyword, because the volatile keyword can not guarantee atomic operations.

Fifth, the end of the

1.always keep the faith!!!

Published 122 original articles · won praise 64 · views 50000 +

Guess you like

Origin blog.csdn.net/chenmingxu438521/article/details/103764641