The basic realization principle of Lock interface

        In the implementation of the Lock interface, there is a well-known one called ReentrantLock. Its implementation mechanism relies on its internal class Sync, which is a subclass of AbstractQueuedSynchronizer (AQS). The main function of this class is to manage the synchronization state by managing a two-way synchronization queue (FIFO), and realize the security of multi-thread access to the synchronization state. The data structure stored in the synchronization queue is a node Node, which contains references to forward nodes and subsequent nodes similar to a doubly linked list, as well as subsequent waiting node references and constructed threads. The nodes in the waiting queue to be discussed later are the same definitions as this.

            For users, it is only necessary to understand that the synchronization queue is managed by the synchronizer through two directional references. The following is the basic structure diagram:

, if a thread fails to obtain the synchronization state, it will try to enter the tail of the synchronization queue through the compareAndSetTail (Node expect, Node update) method of the synchronizer and replace the original tail reference. The condition for dequeuing the synchronization queue is that the current node is the first node, and the current node obtains the synchronization state successfully. After being dequeued, subsequent nodes will be woken up to try to obtain the synchronization state. However, there are two implementation strategies for obtaining the synchronization state. One is to obtain the synchronization state exclusively (Node.EXCLUSIVE), that is, at most one thread can obtain the synchronization state at the same time, and the others do not. The synchronous queue is added through add'Waiter. The other is shared, which allows multiple threads to obtain synchronization state at the same time (Node.SHARED)

        ConditionObject, a subclass of the Condition interface, is also aggregated inside Sync, which provides a monitor method similar to Object to cooperate with Lock to implement the waiting notification mode. Each Condition comes with a waiting queue. After a thread calls the await method, it will be transferred from the synchronization queue to the waiting queue. The waiting queue is actually a singly linked list, similar to a synchronizer, which saves References to the head node and tail node, other methods are similar to synchronous queues. Only when a thread calls the signal method of the condition (wake up the first node), it can be transferred from the waiting queue to the synchronization queue.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325732743&siteId=291194637