Java Multithreading (i) Race condition phenomenon and its causes

Source: Internet
Author: User

Reprint Please specify the source http://blog.csdn.net/xingjiarong/article/details/47603813

What is race Condition

First of all, what is Race condition? Race condition Chinese translation is a competitive condition that refers to a phenomenon in which multiple processes or threads concurrently access and manipulate the same data and perform results that are related to the particular order in which the access occurs. In other words, the order in which data is accessed between threads or processes determines the result of data modification, a phenomenon that is often seen in multithreaded programming.

Race Condition Instances

Class MyThread implements Runnable {/** * calculation type, 1 for subtraction, others for addition * /    Private intType Public MyThread(intType) { This. type = type; } Public void Run() {if(Type = =1) for(inti =0; I <10000; i++) test.num--;Else             for(inti =0; I <10000;    i++) test.num++; }} Public  class Test {     Public Static intnum =1000000; Public Static void Main(string[] args) {Thread A =NewThread (NewMyThread (1)); Thread B =NewThread (NewMyThread (2));        A.start (); B.start ();/ * * The main thread waits for the child thread to finish before printing the value */        Try{A.join ();        B.join (); }Catch(Exception e)        {E.printstacktrace ();    } System.out.println (num); }}

The above program is very simple. is to use two threads to manipulate and modify the same data at the same time, one thread wants to add num 10000, another thread wants to reduce NUM by 10000, according to our calculations, a number plus 10000, minus 10000, the equivalent of no change, so the result should be equal to himself. But it's just our imagination, is that really the case? You can run the above program, you will be surprised to find that the result is not 1000000, and then run a few more times, is not each time the results are different.
Yes, this is the result of race Condition, with two threads, working with the NUM variable, and the results of the operation are related to the order of access (this is not controlled by the operating system, we can only see the results are different each time).

Causes of Race Condition production

Now that we have seen the phenomenon of race condition, how did it come about? Do not be eager to say, you did not say, because of the different order of access caused. I would like to say that learning new knowledge must be traced, to really understand, then at the hardware or operating system level, the cause of this phenomenon occurs?

First, let's look at a picture.

We know that in the operating system, operating system programs assign separate registers and program counters to each thread. In the diagram above, I have divided into three columns, where the first column represents the operation of the line Cheng, the second column represents the process of the line Cheng, and the third column represents the results in memory. In the first two columns of the graph, a small box with a number indicates the register used by the thread, and the number represents the value in that register. A small box in the third column represents a storage unit in memory that represents a numeric value stored in memory.

Now, let's take a look at the process of operation. (Here is the simplified schematic process, the real process is much more complex) at the beginning of the data are placed in memory, so through the load instruction, num loaded into the register, and then execute the corresponding operation instructions, here is the Add (plus 1) SUB (minus 1) instruction, after the execution of the instruction, The result is stored in the appropriate register, when the value in memory has not changed. After the last store instruction is executed, the values in the register are stored in memory.

The order of the small squares from top to bottom represents the process of alternating execution of thread 1 and thread 2. First, thread 1 reads the value of NUM in memory, then goes to thread 2 execution, reads the value of NUM in memory, then performs minus 1, and finally writes the result back into memory, when the data in memory becomes 999999, but this one changes thread 1 is invisible, Because this change occurs after thread 1 reads the value of Num. In fact, the data read by thread 1 is already incorrect data, which is the root cause of race condition. Then thread 1 executes the unfinished instruction, adds 1 operations, and finally writes 1000001 memory, which is the direct cause of the race condition, which overwrites the results of thread 2.

This is the cause of race condition, do you really understand?

Of course race Condition This phenomenon is not good, so we will be in various ways to avoid the generation of race Condition. In the next blog, I will introduce you if in the Java multithreaded programming to avoid race Condition and multi-threaded synchronization and mutually exclusive content, I hope to learn together with you progress, please continue to follow my blog, if you support my words, the top of me.

Java Multithreading (i) Race condition phenomenon and its causes

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.