Java command sorting

Source: Internet
Author: User

Java command sorting

Reproduced from: http://my.oschina.net/004/blog/222069? Fromerr = ER2mp62C

Command Re-sorting is a complicated and incredible problem. It also begins with an example (we recommend that you run the example below, which is actually reproducible, the probability of re-sorting is still quite high), there is a perceptual knowledge

/*** A simple example of Happen-Before. * There are two shared variables: a and flag. The initial values are 0 and false, respectively. in ThreadA, first give a = 1, then flag = true. * if it is sorted, if (flag) is successful in ThreadB, it should be a = 1, and after a = a * 1, a is still 1, if (a = 0) below should never be * true, never print. * But the actual situation is: 0 or several times of printing results will appear in the case of 100 tests, and the results of 1000 tests are more obvious, with more than 10 times of printing. */public class SimpleHappenBefore {/** this is a verification result variable */private static int a = 0;/** this is a flag */private static boolean flag = false; public static void main (String [] args) throws InterruptedException {// due to multithreading, the re-sorting conclusion may not be obtained, so try multiple times for (int I = 0; I <1000; I ++) {ThreadA threadA = new ThreadA (); ThreadB threadB = new ThreadB (); threadA. start (); threadB. start (); // wait until the thread ends, reset the shared variable to make the verification result easier. threadA. join (); threadB. join (); a = 0; flag = false ;}} static class ThreadA extends Thread {public void run () {a = 1; flag = true ;}} static class ThreadB extends Thread {public void run () {if (flag) {a = a * 1;} if (a = 0) {System. out. println ("ha, a = 0 ");}}}}

 

The example is relatively simple. Annotations are also added and will not be described in detail.
What is Command Re-sorting? There are two layers:
At the virtual machine level, in order to minimize the impact of CPU vacancy caused by memory operation speed far slower than CPU operation speed, virtual Opportunities follow some of their own rules (this rule will be described later) disrupt the programming order-that is, the code written below may be executed first in the chronological order, and executed after the code written above-to make full use of the CPU as much as possible. Take the preceding example as an example.a=new byte[1024*1024](Allocate 1 MB space) ', then it will run slowly. Does the CPU wait for its execution to end, or does it execute the following flag = true first? Obviously, if you run flag = true first, you can use the CPU in advance to speed up the overall efficiency. Of course, the premise is that no error will be generated (what kind of error will be mentioned later ). Although there are two cases: the subsequent code is executed before the previous Code; the previous code is executed first, but when the efficiency is slow, the subsequent code is executed and ended before the previous code execution. No matter who starts first, the subsequent code may end first in some cases.
On the hardware layer, the CPU sorts a batch of commands according to the rules. It is also based on the reason that the CPU speed is faster than the cache speed. The purpose is similar to the previous one, if hardware processing is used, the system can only re-sort the received commands within a limited range, while virtual machines can re-sort the commands within a larger scope. For details about the hardware re-sorting mechanism, see view CPU Memory command re-sorting (Memory Reordering) from JVM concurrency.
Reordering is hard to understand. The preceding section simply mentions the scenario. To better understand this concept, we need to construct some examples and charts, here we will introduce two more detailed and vivid articles, happens-before, and Java Memory Model (II)-reordering. The "as-if-serial" should be mastered, that is, the execution results of a Single-threaded program cannot be changed no matter how the program is re-ordered. The compiler, runtime, and processor must comply with the "as-if-serial" syntax. For example,

public void execute(){    int a=0;    int b=1;    int c=a+b;}

 

 

Here, a = 0 and B = 1 can be sorted without affecting the logic result of the program. However, c = a + B must be followed by the first two sentences.
From the previous example, we can see that the probability of occurrence of reordering in a multi-threaded environment is quite high. volatile and synchronized keywords can be used to disable the re-sorting. In addition, there are some rules, it is precisely these rules that make us feel the disadvantages of re-sorting in our daily programming work.
Program Order Rule: In a thread, the previous operations are written in the code Order first in the subsequent operations. Accurately speaking, it should be the control flow order rather than the code order, because the branch, loop, and other structures should be considered.
Monitor Lock Rule: an unlock operation first occurs before the lock operation on the same object Lock. The same lock is emphasized here, and "later" refers to the sequence of time, such as the lock operation that occurs in other threads.
Volatile Variable Rule (Volatile Variable Rule): write operations on a volatile Variable occur after the read operations on this Variable are performed, the "back" here also refers to the chronological order.
Thread Start Rule: the start () method exclusive to the Thread goes first for every action of this Thread.
Thread Termination Rule (Thread Termination Rule): Each operation in the Thread first performs a Termination check on the Thread. We can use the Thread. join () method end, Thread. the returned value of isAlive () indicates that the thread has terminated the execution.
Thread Interruption Rule: the call to the Thread interrupte () method takes precedence over the occurrence of the interrupt event detected by the code of the interrupted Thread. You can use the Thread. the interrupted () method checks whether the thread has been interrupted.
Finalizer Rule: the initialization of an object (the execution of the constructor ends) first occurs at the beginning of its finalize () method.
Transititability: If operation A first occurs in operation B and operation B first occurs in operation C, the conclusion that operation A first occurs in operation C can be drawn.
These rules ensure the order of happen-before. If they do not comply with the preceding rules, the execution sequence cannot be the same as the code sequence in a multi-threaded environment, that is, "If we observe in this thread, all operations are ordered; if we observe another thread in one thread, all operations that do not comply with the above rules are disordered". Therefore, if our multi-threaded program depends on the code writing sequence, we need to consider whether it complies with the above rules. If it does not comply with the rules, we need to use some mechanisms to make it comply, synchronized, Lock, and volatile modifiers are commonly used.

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.