AQS core idea
If the requested shared resource is free, then the current thread is set to a valid request worker threads, and a shared resource to a locked state. If the shared resource is requested is occupied, then you need to wake up and wait for a thread to block mechanism that is used CLH queue to achieve, will temporarily get less lock thread added to the queue
AQS share resources
AQS maintains a volatile int state (shared resources) and a CLH queue; the way in which the state visit of three ways:
- getstate()
- setState()
- compareAndSetState ()
AQS defines two resource sharing: Exclusive (exclusive, only one thread can perform, such as ReentrantLock) and Share (shared, multiple threads can be executed simultaneously, such as CountDownLatch)
AQS synchronizer
- isHeldExclusively (): if the threads are monopolizing resources
- tryAcquire (): exclusive, try to acquire resources
- tryRelease (): exclusive, try to free resources
- tryAcquireShared (): sharing, try to acquire resources
- tryReleaseShared (): sharing, try to free resources
As an example of implementation of CoundDownLatch, is divided into N sub-task to execute threads, also initialized state N, each child thread executed after completion of the countDown () once, a state will be reduced at the CAS operation, when the zero state Save unpark (wake-up) main calling thread
Read lock and write lock (exclusive and shared) implementation
The CLH queue mode of a node is EXCLUSIVE and SHARED mode, when a thread successfully modified state condition indicates a lock is acquired, the node if the thread is located as SHARED mode, will start a process lock pass read, the head node, to transmission queue wakeup subsequent node, or until the end of the queue node encountered EXCLUSIVE mode, waiting for the read operation is completed all active, and then proceeds to EXCLUSIVE mode