1. Basic research of AQS

AQS: AbstractQueuedSynchronizer, abstract queue synchronizer, is in Java synchronizer and locking mechanism to realize the base class, it is mainly used for encapsulation of thread queue, and through the use of template method, a set of access to release the lock mechanism of template, Developers only need to implement a few protected methods to implement features such as locking.

2. AQS interview questions

  1. Common variables and methods and functions in AQS
  • The state variable

private volatile int state; State ==0 when initialized, state==1 when one thread succeeds; When other threads see that state is not equal to 0, they determine that it is occupied.

  • AbstractOwnableSynchronizer class

There is only one variable in this class: ‘exclusiveOwnerThread’ and its corresponding set/ GET method, which identifies the current thread holding the lock in the exclusive lock state

public abstract class AbstractOwnableSynchronizer
    implements java.io.Serializable {

    /** Use serial ID even though all fields transient. */
    private static final long serialVersionUID = 3737899427754241961L;
    protected AbstractOwnableSynchronizer(a) {}private transient Thread exclusiveOwnerThread;
    protected final void setExclusiveOwnerThread(Thread thread) {
        exclusiveOwnerThread = thread;
    }
    protected final Thread getExclusiveOwnerThread(a) {
        returnexclusiveOwnerThread; }}Copy the code
  • How to use AQS to write your own synchronizer

Just override a few protected methods in AQS

    a. tryAcquire(int arg);
    b. tryRelease(int arg);
    c. tryAcquireShared(int arg)
    d. tryReleaseShared(int arg);
Copy the code

AQS makes full use of template methods, such as acquire lock (int ARG) method

    public final void acquire(int arg) {
        // We need to implement tryAcquire(int arg)
        if(! tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }Copy the code

3. Practical application of AQS

The underlying implementation of Todo ReentrantLock, CountDownLatch, and Semphore is AQS.

Copy the code