Sike java synchronized series of AQS final chapter (Interview)

problem

(1) AQS positioning?

An important part (2) AQS is?

(3) AQS use design patterns?

(4) the overall flow of AQS?

Brief introduction

AQS stands AbstractQueuedSynchronizer, it is positioned to provide a basic framework for virtually all of the locks in Java and the synchronizer.

In the previous chapter, we learned together ReentrantLock, ReentrantReadWriteLock, Semaphore, CountDownLatch source, and today we come together to be a summary of AQS.

State variable state

AQS defines a state variable state, it has the following two methods:

(1) a mutex

AQS only when implemented as a mutex, so long as each atomic state update value from 0 to 1 on a lock is acquired successfully, reentrant is achieved by continuously adding an atomic update the state.

(2) + shared lock a mutex

When AQS need to be implemented as a mutex + shared lock when the lower 16 bits are stored mutex state, state of the high 16-bit memory shared lock, is mainly used for read-write lock.

Mutex is an exclusive lock, allows only one thread exclusive, and when a thread exclusive, other threads will not be able to acquire the mutex lock and a shared lock, but they can acquire a shared lock.

Shared lock allows multiple threads simultaneously occupy, as long as there is a thread owns a shared lock, all threads (including myself) will no longer acquire the mutex but may acquire a shared lock.

AQS queue

AQS maintained in a queue to obtain a lock failure (non tryLock ()) thread will enter this queue in the queue, waiting for the next wake up after the release of a lock queue thread (under exclusive lock mode).

Condition queue

AQS there is another very important internal class ConditionObject, which implements the Condition interface is mainly used for lock condition.

ConditionObject also maintains a queue which is mainly used for the establishment of waiting for the condition, when the condition is satisfied, the other threads will signal elements in the queue, move it to the AQS queue, waiting possession of the lock thread releases the lock wake up.

Condition typical use scenario is implemented in BlockingQueue is, when the queue is empty, retrieving an element threads blocked on notEmpty conditions, once the queue is added an element, we will inform notEmpty conditions, to move its queue elements to the AQS the queue waiting to be awakened.

Template Method

AQS this abstract class to use the Template Method design pattern pinnacle, which it defines a set of template methods, such as those below:

// 获取互斥锁
public final void acquire(int arg) {
    // tryAcquire(arg)需要子类实现
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}
// 获取互斥锁可中断
public final void acquireInterruptibly(int arg)
        throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    // tryAcquire(arg)需要子类实现
    if (!tryAcquire(arg))
        doAcquireInterruptibly(arg);
}    
// 获取共享锁
public final void acquireShared(int arg) {
    // tryAcquireShared(arg)需要子类实现
    if (tryAcquireShared(arg) < 0)
     doAcquireShared(arg);
}
// 获取共享锁可中断
public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    // tryAcquireShared(arg)需要子类实现
    if (tryAcquireShared(arg) < 0)
        doAcquireSharedInterruptibly(arg);
}
// 释放互斥锁
public final boolean release(int arg) {
    // tryRelease(arg)需要子类实现
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}
// 释放共享锁
public final boolean releaseShared(int arg) {
    // tryReleaseShared(arg)需要子类实现
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}
复制代码

Acquiring the lock, the lock release these methods basically interspersed in ReentrantLock, ReentrantReadWriteLock, Semaphore, CountDownLatch source code parsing, and now to see if they are not comfortable, if you start to see the source code, it will be very faint.

Subclass method needs to achieve

AQS above learning together in several important template method, the following method at a few and then we need to achieve sub-class learning together:

// 互斥模式下使用:尝试获取锁
protected boolean tryAcquire(int arg) {
    throw new UnsupportedOperationException();
}
// 互斥模式下使用:尝试释放锁
protected boolean tryRelease(int arg) {
    throw new UnsupportedOperationException();
}
// 共享模式下使用:尝试获取锁
protected int tryAcquireShared(int arg) {
    throw new UnsupportedOperationException();
}
// 共享模式下使用:尝试释放锁
protected boolean tryReleaseShared(int arg) {
    throw new UnsupportedOperationException();
}
// 如果当前线程独占着锁,返回true
protected boolean isHeldExclusively() {
    throw new UnsupportedOperationException();
}
复制代码

Why these methods are not directly defined as abstract methods?

Subclasses implement as long as a portion of these methods can achieve a synchronizer, and there is no need to define the abstract methods.

to sum up

Today we talk about a few important components under AQS, a thoroughly understand these structures, AQS you will not have any secrets at all, of course, the interview can answer these points clear, the interviewer will an impact.

(1) State of state variables;

(2) AQS queue;

(3) Condition queue;

(4) template method;

(5) to be subclassed implemented method;

Egg

After the previous study, you can get a brief description of AQS mutex general process it?

Tong brother is not here to answer, I believe learning the preceding sections, answer this question is not a problem, could not answer the need to make the following recommendation to read a good Duokanjibian ^^

Recommended Reading

1, Sike java synchronization of the Opening Series

2, Sike Unsafe java class of analytic magic

3, Sike java synchronized series of JMM (Java Memory Model)

4, Sike java synchronized series of volatile resolve

5, Sike java synchronized series of synchronized resolve

6, Sike java series of synchronous write himself a lock Lock

7, Sike java synchronized series of articles from the AQS

8, Sike ReentrantLock resolve java source code synchronized series of (a) - fair locks, lock unfair

9, Sike ReentrantLock resolve java source code synchronized series of (two) - Conditions Lock

10, Sike java synchronized series of ReentrantLock VS synchronized

11, Sike ReentrantReadWriteLock parse java source synchronous series

12, Sike Semaphore synchronization java source parsing Series

13, Sike java source parsing synchronous series CountDownLatch

I welcome the attention of the public number "Tong brother read source" view source code more series, and brother Tong source of ocean swim together.

qrcode

Guess you like

Origin juejin.im/post/5d0d4df7518825324d099665