多线程同步器AQS

来源:互联网 发布:charles游戏修改数据 编辑:程序博客网 时间:2024/06/06 03:05

介绍

AQS是AbstractQueuedSynchronizer的缩写,AbstractQueuedSynchronizer类是很多cuncurrent.lock是包中的Lock的实现类,常见的ReentrantLock(可重入锁)、ReadWriteLock(读写锁)。

public abstract class AbstractQueuedSynchronizer    extends AbstractOwnableSynchronizer    implements java.io.Serializable {    private static final long serialVersionUID = 7373984972572414691L;    ...    protected AbstractQueuedSynchronizer() { }    // 队列头    private transient volatile Node head;    // 队列尾    private transient volatile Node tail;    // 同步状态    private volatile int state;    ...

AQS是用来构建锁和其他同步组件的基础框架。state是用于表示同步状态,队列是FIFO的队列,用于完成资源获取线程的排队工作。volatile的队列头和队列尾。

Node代码

static final class Node {        static final Node SHARED = new Node();        static final Node EXCLUSIVE = null;        static final int CANCELLED =  1;        static final int SIGNAL    = -1;        static final int CONDITION = -2;        static final int PROPAGATE = -3;        volatile int waitStatus;        volatile Node prev;        volatile Node next;        volatile Thread thread;        Node nextWaiter;        final boolean isShared() {            return nextWaiter == SHARED;        }        final Node predecessor() throws NullPointerException {            Node p = prev;            if (p == null)                throw new NullPointerException();            else                return p;        }        Node() {        }        Node(Thread thread, Node mode) {     // Used by addWaiter            this.nextWaiter = mode;            this.thread = thread;        }        Node(Thread thread, int waitStatus) { // Used by Condition            this.waitStatus = waitStatus;            this.thread = thread;        }    }

Head节点代表当前持有锁的线程,每当线程竞争失败,则插到队列的尾节点。
tail节点始终指向队列最后的一个元素。
waitStatus代表每个节点当前的状态,具有四种状态:
1. CANCELLED 取消状态
2. SIGNAL 等待触发状态
3. CONDITION 等待条件状态
4. PROPAGATE 状态需要向后传播
队列是FIFO,只有前一个节点为SIGNAL的时候,当前节点才能被挂起。

获取锁原理

tryAcquire和tryRelease方法修改state

public final void acquire(int arg) {    if (!tryAcquire(arg) &&        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))        selfInterrupt();}

获取锁的过程

拟定线程A和线程B进行竞争。
1. 线程A执行CAS执行成功,state值被修改并返回true,线程A继续执行。
2. 线程A执行CAS失败,说明线程B也在执行CAS指令且成功,这种情况A执行步骤3。
3. 生成新Node节点node,并通过CAS指令插入到对位,如果tail为空,则将head节节点指向另一个空节点,应该是线程B。

private Node addWaiter(Node mode) {     Node node = new Node(Thread.currentThread(), mode);     // Try the fast path of enq; backup to full enq on failure     Node pred = tail;     if (pred != null) {         node.prev = pred;         if (compareAndSetTail(pred, node)) {             pred.next = node;             return node;         }     }     enq(node);     return node;}private Node enq(final Node node) {     for (;;) {         Node t = tail;         if (t == null) { // Must initialize             if (compareAndSetHead(new Node()))                 tail = head;         } else {             node.prev = t;             if (compareAndSetTail(t, node)) {                 t.next = node;                 return t;             }         }     }}
  1. node插入到队尾后,该线程不会立马挂起,会进行自旋操作。因为在node的插入过程,线程B(即之前没有阻塞的线程)可能已经执行完成,所以要判断该node的前一个节点pred是否为head节点(代表线程B),如果pred == head,表明当前节点是队列中第一个“有效的”节点,因此再次尝试tryAcquire获取锁,
    1)如果成功获取到锁,表明线程B已经执行完成,线程A不需要挂起。
    2)如果获取失败,表示线程B还未完成,至少还未修改state值。进行步骤5。
final boolean acquireQueued(final Node node, int arg) {    boolean failed = true;    try {        boolean interrupted = false;        for (;;) {            final Node p = node.predecessor();            if (p == head && tryAcquire(arg)) {                setHead(node);                p.next = null; // help GC                failed = false;                return interrupted;            }            if (shouldParkAfterFailedAcquire(p, node) &&                parkAndCheckInterrupt())                interrupted = true;        }    } finally {        if (failed)            cancelAcquire(node);    }}
  1. 如果前一个节点pred的线程状态为SIGNAL时,当前节点才能被挂起。
    1)如果pred的waitStatus == 0,则通过CAS指令修改waitStatus为Node.SIGNAL。
    2)如果pred的waitStatus > 0,表明pred的线程状态CANCELLED,需从队列中删除。
    3)如果pred的waitStatus为Node.SIGNAL,则通过LockSupport.park()方法把线程A挂起,并等待被唤醒,被唤醒后进入步骤6。
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {    int ws = pred.waitStatus;    if (ws == Node.SIGNAL)        return true;    if (ws > 0) {        do {            node.prev = pred = pred.prev;        } while (pred.waitStatus > 0);        pred.next = node;    } else {        compareAndSetWaitStatus(pred, ws, Node.SIGNAL);    }    return false;}
  1. 线程每次被唤醒时,都要进行中断检测,如果发现当前线程被中断,那么抛出InterruptedException并退出循环。从无限循环的代码可以看出,并不是被唤醒的线程一定能获得锁,必须调用tryAccquire重新竞争,因为锁是非公平的,有可能被新加入的线程获得,从而导致刚被唤醒的线程再次被阻塞,“非公平”锁就是这个设置。

释放锁的过程

  1. 如果头结点head的waitStatus值为-1,则用CAS指令重置为0;
  2. 找到waitStatus值小于0的节点s,通过LockSupport.unpark(s.thread)唤醒线程。
private void unparkSuccessor(Node node) {    int ws = node.waitStatus;    if (ws < 0)        compareAndSetWaitStatus(node, ws, 0);    Node s = node.next;    if (s == null || s.waitStatus > 0) {        s = null;        for (Node t = tail; t != null && t != node; t = t.prev)            if (t.waitStatus <= 0)                s = t;    }    if (s != null)        LockSupport.unpark(s.thread);}
原创粉丝点击