[Java Concurrency Introduction] 01 The source of concurrent programming bugs

1. Root cause

"Speed ​​Difference Between CPU, Memory, Disk"

  • In order to perform multiple tasks at the same time, the CPU has developed time slice rotation, multi-core, etc.
  • The CPU is too slow to read data from memory, so it sets up a cache for itself
  • The CPU reads the disk more slowly, so the thread can be blocked

2. The direct cause

Visibility issues caused by caching

The CPU loads the data to be processed into its own cache, and puts it back into its own cache after processing.

If another CPU performs the same processing, the result of the previous CPU processing may not be seen.

Atomicity problems caused by thread switching

A line of code in a program is often not a CPU instruction.

When a thread is switched, it may be switched in the middle of a code execution.

The order problem caused by compilation optimization

Optimization rearranges code instructions for more efficient use of CPU cache.

This rearrangement process will lead to code that seems to be fine, and logic problems in multi-threading.

Third, why do we encounter these problems

  • To improve program performance
  • When a new method is introduced, it is necessary to deal with the problems corresponding to this method
  • It can be said that hardware engineers and operating system engineers have brought trouble to software engineers in order to improve execution efficiency.

The next few articles will introduce how to solve the problems of "visibility, atomicity, and order" mentioned above.

Guess you like

Origin blog.csdn.net/shuofxz/article/details/128085138