Questions about reordering Java commands

Source: Internet
Author: User

Reprinted from: Http://my.oschina.net/004/blog/222069?fromerr=ER2mp62C

Order reordering is a more complex, feel some incredible problem, the same is the first example (recommended to run the next example, which is actually reproducible, the probability of reordering is very high), there is a perceptual understanding

/*** A simple example showing happen-before. * Here are two shared variables: A and flag, with an initial value of 0 and false. First give a=1 in Threada, then flag=true. * If ordered, then in THREADB If the flag succeeds then it should be a=1, and after a=a*1 A is still 1, the below if (a==0) should never be * True and will never print. * But the actual situation is: In the case of test 100 times there will be 0 or several printing results, and the test 1000 times more obvious results, more than 10 times printing. */ Public classSimplehappenbefore {/**This is a variable that validates the result*/    Private Static intA=0; /**This is a flag bit*/    Private Static Booleanflag=false;  Public Static voidMain (string[] args)throwsinterruptedexception {//because of the multi-threaded situation may not try to reorder the conclusion, so try a few times         for(inti=0;i<1000;i++) {Threada Threada=NewThreada (); THREADB threadb=Newthreadb ();            Threada.start ();            Threadb.start (); //after waiting for the thread to end, reset the shared variable so that the validation results are easier to work with.Threada.join ();            Threadb.join (); A=0; Flag=false; }    }    Static classThreadaextendsthread{ Public voidRun () {a=1; Flag=true; }    }    Static classThreadbextendsthread{ Public voidrun () {if(flag) {a=a*1; }            if(a==0) {System.out.println ("Ha,a==0"); }        }    }}

The

example is simple and adds comments that are not described in detail.
What is command reordering? There are two levels:
at the virtual machine level, in order to minimize the effect of memory operations much slower than the CPU vacancy caused by the speed of CPUs, the virtual machines in accordance with some of their own rules (this rule is described later) the programming order of the program is scrambled-that is, the code written in the following time sequence may be executed first, And the code written in front of it will be executed after that--to make the best use of the CPU. Take the example above: if it is not a=1 operation, but A=new byte[1024*1024] (allocate 1M space) ', then it will run slowly, when the CPU is waiting for its execution to end, or first execute the following sentence flag=true it? Obviously, the first implementation of the flag=true can be used in advance of the CPU, speed up overall efficiency, of course, the premise is not to produce errors (after what kind of error). Although there are two cases, the following code begins with the previous code, and the preceding code begins execution, but when the efficiency is slow, the subsequent code starts executing and ends with the previous code execution. No matter who starts first, in short, the following code in some cases there is a possibility to end first.
at the hardware level, the CPU will receive a batch of instructions in accordance with its rules, the same is based on the CPU faster than the cache speed, and similar to the purpose of the previous point, only hardware processing, each time only in the limited range of instructions received, and the virtual machine can be at a larger level, Reorder within the scope of more instructions. Hardware reordering mechanism see CPU Memory command reordering from JVM concurrency [memory reordering]
reordering is very difficult to understand, the above is simply to mention its scene, to better understand the concept, need to construct some examples and diagrams, Here are two articles introducing a more detailed and vivid article "Happens-before" and "in-depth understanding of Java memory Model (ii)-reordering". One of the "as-if-serial" should be mastered, namely: no matter how to reorder, the implementation of the single-threaded the results can not be changed. The compiler, runtime, and processor must adhere to the "as-if-serial" semantics. To take a simple example,

 Public void Execute () {    int a=0;     int b=1;     int c=a+b;}

Here a=0,b=1 two sentences can be arbitrarily ordered, do not affect the program logic results, but c=a+b this sentence must be executed in the back of the first two sentences.
As you can see from the previous example, the probability of reordering in a multithreaded environment is still quite high, there are volatile and synchronized on the keywords can disable reordering, but there are some rules, it is these rules, So that we do not feel the reordering of the bad in the normal programming work.
Program Order rule: Within a thread, in the order of code, the preceding operation occurs in the previous action. It should be accurate to control the flow order rather than the code order, because the structure of branching, looping, etc. is considered.
Monitor lock rule: A unlock operation first occurs after a lock operation that faces the same object locks. The emphasis here is on the same lock, while the "back" refers to the chronological order of the time, such as the lock operation that occurs in other threads.
Volatile variable rules (volatile Variable rule): Writes to a volatile variable occur after the read operation of the variable, where the "back" also refers to the chronological order.
Thread start rule: The Threads exclusive Start () method precedes each action of this thread.
Thread termination rule: each operation in the thread precedes the termination detection of this thread, and we can detect that the thread has terminated execution by the Thread.Join () method end, the return value of thread.isalive ().
Thread interruption rule: The call to the thread Interrupte () method takes precedence over the code of the interrupted thread to detect that the interrupt event occurred, and the thread can be detected by the thread.interrupted () method.
Object termination principle (Finalizer rule): The initialization of an object (the end of the execution of a constructor) occurs first at the beginning of its finalize () method.
Transitivity (transitivity): If operation a first occurs in operation B, Operation B first occurs in Operation C, it can be concluded that operation a precedes operation C.
It is these rules that guarantee the order of the Happen-before, and if they do not conform to the above rules, there is no guarantee that the execution order is equivalent to the code order in a multithreaded environment, i.e. "if you observe in this thread, all operations are orderly; If you observe another thread in one thread, does not conform to the above rules are unordered, so if our multi-threaded program depends on the code writing order, then we should consider whether to conform to the above rules, if the non-conformance will be through some mechanism to conform to, the most commonly used is synchronized, lock and the volatile modifier.

Questions about reordering Java commands

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.