The atomicity, visibility, and ordering of Java concurrency

Source: Internet
Author: User

Objective

In the form of concurrent programming, the computing power of multi-core CPUs can be reached to the extreme, performance is improved, allowing us to make full use of system resources, at the same time, must ensure atomicity, order, visibility, to ensure that the program does not have problems

One, atomicity (1) explanation

Atomicity refers to one or more operations that are either executed completely and not interrupted by other actions during execution, or are not executed at all

(2) Analysis
分析以下代码,判断哪些是原子性的x=10;//语句1y=x;//语句2x++;//语句3x=x+1;//语句4

See the above code may be small partners will say is atomic, but in fact, only statement 1 is atomic.

x=10, when the thread executes the statement, writes the value 10 directly to the working memory

Y=x, when a thread executes this statement, it first reads the value of x from the working memory, and then writes the value of X to the working memory, although both are atomic, but not together.

X + +, when the thread executes this statement, it essentially performs three actions, reads the x. From the working memory, performs +1, and writes the final result to the working memory.

In other words, in the Java memory model, only simple reads and assignments to the basic data types are atomic (the reciprocal assignment is not atomic).

A single read/write operation on a volatile variable guarantees atomicity, such as long and double type variables, but does not guarantee the atomicity of the i++ operation, because essentially i++ is read and write two operations.
Because the operation of a long and a double of two data types can be divided into high 32-bit and low 32-bit two parts, the normal long or double type read/write may not be atomic. Therefore, it is encouraged to set the shared long and double variables to the volatile type, which ensures that a single read/write operation of Long and double is atomic in any case.

package com.paddx.test.concurrent;public class VolatileTest01 {volatile int i;public void addI(){    i++;}public static void main(String[] args) throws InterruptedException {    final  VolatileTest01 test01 = new VolatileTest01();    for (int n = 0; n < 1000; n++) {        new Thread(new Runnable() {            @Override            public void run() {                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }                test01.addI();            }        }).start();    }    Thread.sleep(10000);//等待10秒,保证上面程序执行完成    System.out.println(test01.i);//结果为981}}详解:大家可能会误认为对变量i加上关键字volatile后,这段程序就是线程安全的。可能每个人运行的结果不相同。不过应该能看出,volatile是无法保证原子性的(否则结果应该是1000)。原因也很简单,i++其实是一个复合操作,包括三步骤:(1)读取i的值。(2)对i加1。(3)将i的值写回内存。

Volatile is no guarantee that these three operations are atomic, and we can guarantee the atomicity of +1 operations by Atomicinteger or synchronized.

(3) Realize

Ways to achieve a wide range of atomicity:

Pessimistic lock (synchronized or lock)

Optimistic lock (Atomic class CAs)

Ii. Visibility (1) explanation

Visibility when multiple threads manipulate a shared variable, one of the threads modifies the variable, and other threads can immediately see the result of the modification.

(2) Analysis

When the computer executes the program, each instruction is executed in the CPU, while the execution of the instruction is bound to involve the reading and writing of the data. Since the temporary data in the program is stored in main memory (physical RAM), there is a problem, because the CPU is executing fast, and the process of reading data from memory and writing data to memory is much slower than the CPU executing instructions. Therefore, if the operation of the data at any time through the interaction with the memory, it will greatly reduce the speed of instruction execution. So there's a cache in the CPU.

In other words, when the program is running, the data required for the operation is copied from main memory to the CPU cache, then the CPU can read and write data directly from its cache, and when the operation is finished, the data in the cache is flushed to main memory.

  Package Com.paddx.test.concurrent;public class Volatiletest {int a = 1;int b = 2;public void change () {a = 3    ; b = A;} public void print () {System.out.println ("b=" +b+ "; a=" +a);}        public static void Main (string[] args) {while (true) {final volatiletest test = new Volatiletest (); New Thread (New Runnable () {@Override public void run () {try {Th                Read.sleep (10);                } catch (Interruptedexception e) {e.printstacktrace ();            } test.change ();        }}). Start (); New Thread (New Runnable () {@Override public void run () {try {Th                Read.sleep (10);                } catch (Interruptedexception e) {e.printstacktrace ();            } test.print ();    }}). Start (); }}}

Explain:
Intuitively, the result of this code is only possible in two ways: B=3;a=3 or b=2;a=1. But running the above code (perhaps a little longer in time), you'll see a third result in addition to the last two results:
Why does it appear b=3;a=1 this result? Under normal circumstances, if the change method is executed before the Print method is executed, the output should be b=3;a=3. Conversely, if the Print method is executed first and then the change method is executed, the result should be b=2;a=1. How did the b=3;a=1 result come out? The reason is that the first thread modifies the value a=3, but it is not visible to the second thread, so this result occurs. If both A and B are changed to a volatile type of variable, then the result of b=3;a=1 will no longer occur.

(3) Realize

Ways to achieve visibility:

Synchronized or lock: to ensure that only one thread acquires the lock execution code at the same time, the lock is released before the current value is flushed to the main memory for visibility.

Volatile: Volatile modified variables, a thread modified to directly write the value to the main memory, other threads directly from the main memory read.

Third, order (1) explanation

Order, that is, the execution sequence of the program is executed according to the order of the Code.

(2) Analysis

command reordering, in general, the processor may optimize the input code in order to improve the efficiency of the program, and it does not guarantee that the execution order of each statement in the program is consistent with the order in the code, but that it ensures that the results of the final execution of the program and the execution of the code order are consistent.

The processor will consider the data dependencies between instructions when reordering, and if an instruction instruction 2 must use the results of instruction 1, then the processor guarantees that instruction 1 will be executed before instruction 2.

Look at one more example of multithreading:

//volatile boolean inited = false;//线程1:context = loadContext(); inited = true; //线程2:while(!inited ){sleep()}doSomethingwithconfig(context);

In the above code, because statement 1 and statement 2 have no data dependencies, they may be reordered. If there is a reordering, thread 1 executes the first statement 2, and this is the case that the initialization of the work is done, then will jump out of the while loop, to execute the Dosomethingwithconfig (context) method, When the context is not initialized, it causes the program to fail.
As can be seen from the above, command reordering does not affect the execution of a single thread, but it affects the correctness of concurrent execution of threads.
In other words, it is necessary to ensure atomicity, visibility, and order in order for concurrent programs to execute correctly. As long as one is not guaranteed, it may cause the program to run incorrectly.

If the inited variable is decorated with the volatile keyword, this problem does not occur because the context is guaranteed to be initialized when executing to statement 2 o'clock.

(3) Realize

Ways to achieve order:

Synchronized or lock

Volatile (prohibit command reordering)
By the way:

Iv. principle and realization mechanism of volatile

Some of the uses of the volatile keyword are described earlier, so let's look at how volatile guarantees visibility and suppresses command reordering.

The following is an excerpt from the in-depth understanding of Java Virtual machines:

"Observing the addition of the volatile keyword and the assembly code generated when the volatile keyword was not added, a lock prefix instruction is added when adding the volatile keyword"

The lock prefix instruction is actually equivalent to a memory barrier (also a memory fence), and the memory barrier provides 3 functions:

1) It ensures that the command reordering does not place the instructions behind the memory barrier and does not queue the preceding instruction behind the memory barrier, i.e., the operation in front of the memory barrier is completed when the command is executed;

2) It forces the modification of the cache to be immediately written to main memory;

3) If it is a write operation, it causes the corresponding cache line in other CPUs to be invalid.
  

V. Synchronized principle and implementation mechanism (1) synchronized static code block

Decompile a synchronized static code block to see two of the proper nouns
Monitorenter
Each object has a monitor lock. When monitor is occupied, it is locked, and the thread attempts to take ownership of the monitor while executing the monitorenter instruction, as follows:

1. If the monitor has an entry number of 0, the thread enters monitor and then sets the entry number to 1, which is the owner of the Monitor.

2, if the thread already occupies the monitor, just re-enter, then enter the monitor into the number plus 1.

3. If another thread has already occupied monitor, the thread goes into a blocking state until the number of incoming monitor is 0, and then tries to get ownership of monitor again.
monitorexit:
The thread executing the monitorexit must be the owner of the monitor that corresponds to ObjectRef.

When the instruction is executed, the monitor enters the number minus 1, and if the number is 0 after minus 1, the thread exits monitor and is no longer the owner of the Monitor. Other threads that are blocked by this monitor can try to get ownership of the monitor.
  
Summary :
Through these two paragraphs, we should be able to clearly see the implementation of the principle of synchronized, synchronized semantic bottom is through a monitor object to complete, in fact, wait/notify and other methods are also dependent on the monitor object, This is why it is only possible to call wait/notify and other methods in a synchronized block or method, or else the cause of the java.lang.IllegalMonitorStateException exception will be thrown.

(2) Synchronized synchronization method

To decompile a synchronized synchronization method :
acc_synchronized:
From the results of the anti-compilation, the synchronization of the method is not done by the instruction Monitorenter and monitorexit (in theory it can also be achieved by the two instructions), but compared to the normal method, its constant pool has more acc_synchronized identifiers. The JVM implements the synchronization of the method according to the identifier: When the method is called, the calling instruction will check whether the acc_synchronized access flag of the method is set, and if it is set, the execution thread will get the monitor first and then the method body can be executed. The monitor is released after the method has finished executing. No other thread can get the same monitor object during the execution of the method. In fact, there is no difference, but the method of synchronization is an implicit way to achieve, without the bytecode to complete.

The atomicity, visibility, and ordering of Java concurrency

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.