Starting today, I will begin reading "The Art of Concurrency". I learned about this book through the recommendation of a senior student, and it will allow me to have a deeper understanding of concurrent programming. In fact, I have already encountered concurrency issues in my project, but I have never had a systematic study in this area. Now that I have some free time, I will catch up quickly.
PS: I deliberately chose an image related to locks, which also symbolizes sincerity and the opening of a golden lock🔒
1. Context Switching#
Even a single-core processor supports the execution of multiple threads of code. This mechanism is achieved by allocating CPU time slices (usually a few tens of milliseconds) to each thread.
After the current task executes for a time slice, it switches to the next task. Before switching, the state of the previous task is saved so that when switching back to this task, the state can be reloaded. The process of saving and reloading a task is called a context switch.
How to reduce context switching?
- Lock-free concurrent programming. When multiple threads compete for locks, it can cause context switching. Some methods can be used to avoid using locks, such as segmenting data by taking the modulus of their IDs, so that different threads handle different segments of data.
- CAS algorithm: Java's Atomic package uses the CAS algorithm to update data without the need for locks.
- Use the minimum number of threads to avoid creating unnecessary threads.
- Implement task scheduling within a single thread and maintain the switching between multiple tasks within that thread.
2. Deadlock#
Several common methods to avoid deadlock:
- Avoid a thread acquiring multiple locks.
- Avoid a thread simultaneously holding multiple resources within a lock. Try to ensure that each lock only holds one resource.
- Try using timed locks, using lock.tryLock(timeout) instead of using internal lock mechanisms.
- For database locks, locking and unlocking must be done within the same database connection, otherwise unlocking may fail.
3. Challenges of Resource Limitations#
Problem: If a segment of serial code is executed concurrently, it may still be executed serially due to resource limitations. In this case, the program will not only not speed up its execution, but it may even become slower due to the added time for context switching and resource scheduling.
How to solve this:
For hardware resource limitations, use a cluster of machines to execute the program in parallel, with different machines handling different data.
For software resource limitations, consider using a resource pool to reuse resources.
Adjust the concurrency level of the program based on different resource limitations.