The Reentrantlock internally is implemented by the Sync class instance.
The sync class is defined inside Reentrantlock.
Sync inherits from Abstractqueuedsynchronizer.
Abstractqueuedsynchronizer inherits from Abstractownablesynchronizer.
Only one exclusiveownerthread variable is defined in the Abstractownablesynchronizer class that represents the currently owned thread.
In addition to the Sync class, the Reentrantlock internally defines two implementation classes.
Nonfairsync is a non-fair lock. Fairsync is a fair lock.
Reentrantlock two construction methods are as follows:
The lock method of Reentrantlock
Lock method for non-fair locks
The Compareandsetstate method is a CAs method. This method attempts to update a variable within the object. The variable is expected to be 0 and updated to 1.
If the update succeeds, the Exclusiveownerthread variable is set to the current thread. The lock method will then return immediately.
If the update is unsuccessful, call acquire (1).
The Acquire method first calls Tryacquire () to try the update again.
The Tryacquire () method for the non-fair lock is as follows:
The Tryacquire () method for an unfair lock is called internally by the Nonfairtryacquire method as follows:
If the Tryacquire () method tries again unsuccessfully. The Addwaiter () method is called first to join the current thread to the wait queue. The Addwaiter method returns a node.
Once the node is returned, acquirequeued (node,1) tries to do the update again.
If the update is still not possible, the thread is suspended through Parkandcheckinterrupt.
The Unlock method of Reentrantlock
View the release () method.
If the head of the queue is not empty and the wait state of head is not 0, the Unparksuccessor () method is called.
The Unparksuccessor () method is as follows:
Causes node's next to traverse from behind to get to a thread that is waitstatus less than 0 in the front of the queue. Then the threads on the node continue to execute.
Java concurrency--reentrantlock class source Reading