Java concurrent programming summary 7: ReentrantLock

Previous blog: Explaining ReentrantLock in detail

The source code of ReentrantLock is very simple. It implements the AQS framework through internal classes. The implementation of the Lock interface is just a simple encapsulation of the AQS api.

Mainly is the learning of ReentrantLock synchronization semantics:

1. The realization principle of reentrancy;

2. Fair lock and unfair lock. (Default implementation: unfair lock)

 

1. The realization principle of reentrancy

To support reentrancy, two problems must be solved:

1. When a thread acquires a lock, if the thread that has acquired the lock is the current thread, it will be directly acquired again successfully;

2. Since the lock will be acquired n times, the lock is considered to be completely released successfully only after the lock is released the same n times.

Through the study of AQS , we know that the synchronization component mainly expresses its synchronization semantics by rewriting several protected methods of AQS .

The realization of ReentrantLock, taking the unfair lock as an example,

  • Acquire the lock: The core method is nonfairTryAcquire :
  • Release the lock: tryRelease

Fair lock: tryAcqurire:

The logic is basically the same as nonfairTryAcquire. The only difference is that the logical judgment of hasQueuedPredecessors is added . The method name can know that the method is used to judge whether the current node has a predecessor node in the synchronization queue;

If there is a predecessor node, it means that there is a thread that requests resources earlier than the current thread. According to fairness, the current thread fails to request resources;

If the current node does not have a predecessor node, then it is necessary to make subsequent logical judgments. The fair lock acquires the lock from the first node in the synchronization queue every time, while the unfair lock is not necessarily. It is possible that the thread that just released the lock can acquire the lock again .

 

2. Fair locks and unfair locks.

1. Each time a fair lock acquires a lock as the first node in the synchronization queue, the absolute order in the time of requesting resources is guaranteed. An unfair lock may continue to acquire the lock next time when the thread that just released the lock continues to acquire the lock. Other threads can never acquire the lock, causing "starvation" .

2. Fair locks need frequent context switching in order to ensure absolute order in time, while non-fair locks will reduce certain context switching and reduce performance overhead. Therefore, ReentrantLock selects unfair locks by default to reduce some context switching and ensure greater system throughput .

 

 

Guess you like

Origin blog.csdn.net/ScorpC/article/details/113858180