Learn about synchronization from the ground up in java-17.4 (2)-detailed explanation of competition conditions

Source: Internet
Author: User

Learn about synchronization from the ground up in java-17.4 (2)-detailed explanation of competition conditions

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

1. Why does it cause competition?

The operation lacks atomicity.

2. What is atomicity?

The so-called atomic operation is an operation that will not be interrupted by the thread scheduling mechanism. Once this operation starts, it will continue to run until the end, and there will be no context switch (switch to another thread) in the middle ).

3. The procedure for breaking down the transfer in the previous chapter:

(1) read the balance of an account and compare the extracted amount

If (accounts [fromAccount] <money) {return ;}
(2) Transfer xxx RMB from account
Accounts [fromAccount]-= money;

(3) transfer from account B to XXX RMB

Accounts [toAccount] + = money;

4. Because it is not atomic and multi-threaded, we can assume that:

(1) Now thread A has executed the First Step 2 above.

(2) Now thread B is started. Perform Step 1 and Step 2 on the same account.

(An error occurred at this time)

(3) thread A executes step 3.

(4) thread B executes step 3.

Loop ....

We only list the two threads working at the same time, but our test program has 20 threads. In reality, if there may be 20000 or even 2000000 threads, the data will be messed up directly.

5. steps:

6. Worse case

The probability of this error is determined by the time between Step 2 and Step 3. The longer the time, the higher the probability of error occurrence.

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

This chapter is here. Thank you.

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.