From the beginning to know java-17.4 specific explanation synchronization (2)-specific explanation of competitive conditions

Source: Internet
Author: User

In this chapter, we will discuss the competition conditions in detail.

1. Why is there a competitive condition?

Because the operation lacks atomicity.


2. What is atomicity?

Atomic operations are operations that are not interrupted by the thread-scheduling mechanism, which, once started, runs until the end. There will be no context switch in between (switch to a thread).


3. Steps to break down the previous chapter transfer:

(1) Read the remaining amount of an account. Amount extracted from the control

if (Accounts[fromaccount] < money) {return;}

(2) from a account transfer xxx Yuan

Accounts[fromaccount]-= money;


(3) Transfer from B account to xxx yuan

Accounts[toaccount] + = money;


4. Because it is not atomic and is multithreaded, we are able to:

(1) Now thread A has run the first and second steps above

(2) thread B is now started. Take the first second step on the same account

(This time has gone wrong)

(3) Thread A runs the third step

(4) thread B then run the third step

Cycle....

We only listed two threads at the same time, but our test program opened 20 threads. If the reality is that it could be 20000 or even 2 million threads, the data is just going to get out of hand.


5. Step diagram:



6. A worse situation

Because the probability of determining this error is controlled by the time between steps 2 through 3, the longer the time, the higher the probability of the error to occur.


Summary: This chapter mainly discusses the competition conditions in detail.


This chapter is here, thank you.

-----------------------------------

Folder




From the beginning to know java-17.4 specific explanation synchronization (2)-specific explanation of competitive conditions

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.