AbstractQueueSynchronizer源码

来源:互联网 发布:tomcat线程池优化 编辑:程序博客网 时间:2024/05/22 12:49
abstract class java.util.concurrent.locks.AbstarctQueueSynchronizer extends    AbstractOwnableSynchronizer implements java.io.Serializable
  • 1
  • 2

AbstractQueueSynchronizer,简称AQS,是所有的锁类,如ReentrantLock、ReentrantRe 
adWriteLock、CountDownLaunch、Semaphore、ThreadPoolExecutor等实现锁机制的基 

AQS中实现了两套功能:独占功能和共享功能,每一个锁只能有一个功能。 
以文件的查看为例,如果一个程序在对其进行读取操作,那么这一时刻,对这个文件的写操作就被阻塞,相反,这一时刻另一个程序对其进行同样的读操作是可以进行的。如果一个程序在对其进行写操作,那么所有的读与写操作在这一时刻就被阻塞,直到这个程序完成写操作。读操作就是共享操作,写操作就是独占操作。

1.类变量&常量

    private transient volatile Node head;       //等待队列的头部
  • 1
  • 2
    private transient volatile Node tail;       //等待队列的尾部
  • 1
  • 2
    private volatile int state;                 //当前线程的状态
  • 1
  • 2
/* 一系列的unsafe操作private static final Unsafe unsafe = Unsafe.getUnsafe();private static final long stateOffset;private static final long headOffset;private static final long tailOffset;private static final long waitStatusOffset;private static final long nextOffset;static {    try {        stateOffset = unsafe.objectFieldOffset            (AbstractQueuedSynchronizer.class.getDeclaredField("state"));        headOffset = unsafe.objectFieldOffset            (AbstractQueuedSynchronizer.class.getDeclaredField("head"));        tailOffset = unsafe.objectFieldOffset            (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));        waitStatusOffset = unsafe.objectFieldOffset            (Node.class.getDeclaredField("waitStatus"));        nextOffset = unsafe.objectFieldOffset            (Node.class.getDeclaredField("next"));    } catch (Exception ex) { throw new Error(ex); }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

2.构造方法

    protected AbstractQueuedSynchronizer() { }  //为protected方法,只能被子类调用
  • 1

3.内部类

1.ConditionObject类//该类为Condition接口的实现,作为AQS中实现lock的基础,其字段均为transient的 public class ConditionObject implements Condition, java.io.Serializable    private transient Node firstWaiter;    private transient Node lastWaiter;    private Node addConditionWaiter()    //添加一个Node节点进入等待队列    private void doSignal(Node first)    //删除和转移节点    private void doSignalAll(Node first) //删除所有节点,first为队列头结点    private void unlinkCancelledWaiters() //将取消的节点从队列中逸出    public final void signal() {        //删除队列的头结点,通知等待锁的某一个节点        if (!isHeldExclusively())            throw new IllegalMonitorStateException();        Node first = firstWaiter;        if (first != null)            doSignal(first);    }    public final void signalAll() {     //删除队列中所有节点,即通知所有等待锁的结点        if (!isHeldExclusively())            throw new IllegalMonitorStateException();        Node first = firstWaiter;        if (first != null)            doSignalAll(first);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2.Node类,作为等待队列的结点。sync队列对于锁的获取,请求形成节点,将其挂载在尾部,而锁资源的转移(释放再获取)是从头部开始向后进行。    static final Node SHARED = new Node();  //表示节点处于共享功能,即位于condition队列    static final Node EXCLUSIVE = null;     //表示节点处于独占功能,即位于sync队列    /*    状态变量,有以下几种:        SIGNAL:当前节点的后继被阻塞,则当前节点的后继结点的需要被运行,即unpark;        CANCELLED:当前线程被取消        CONDITION:当前节点处于等待Condition队列中,等待Condition        PROPAGATE:当前的场景的后续releasedShared可以被运行        0:表示当前节点在sync队列中,等待着获取锁    */    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匹配的线程    Node nextWaiter;    Node(Thread thread, Node mode) {     // 应用于sync队列        this.nextWaiter = mode;        this.thread = thread;    }    Node(Thread thread, int waitStatus) { // 应用于Conditon队列        this.waitStatus = waitStatus;        this.thread = thread;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

4.重要函数

1. acquire方法,以独占模式运行,忽略中断,完成synchronized语义。arg为状态变量。通过调用至少一次tryAcquire方法并返回true。否则将该线程封装成一个Node节点,并放入sync队列中。然后再次尝试获取,如果没有获取到,则将其从调度器摘下来,并进入等待状态。public final void acquire(int arg) {        if (!tryAcquire(arg) &&            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))            selfInterrupt();    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

image

2.该方法一般被子类重写,用于排他的获取状态protected boolean tryAcquire(int arg) {        throw new UnsupportedOperationException();    }
  • 1
  • 2
  • 3
  • 4
  • 5
3.addWaiter方法,将当前线程包装成一个Node节点,并添加到队列中,返回当前节点    private Node addWaiter(Node mode) {        Node node = new Node(Thread.currentThread(), mode);//判断是Node.EXCLUSIVE用于独占, 还是Node.SHARED用于共享        Node pred = tail;        if (pred != null) {            node.prev = pred;            if (compareAndSetTail(pred, node)) {    //利用原子操作,将node设为tail结点                pred.next = node;                return node;            }        }        enq(node);        return node;    }    //若尾节点为空,即sync队列未初始化,或在addWaiter未成功入队的节点,则会调用该方法    private Node enq(final Node node) {        for (;;) {            Node t = tail;            if (t == null) { // 初始化队列                if (compareAndSetHead(new Node()))                    tail = head;            } else {    //在循环中,可以确保节点全部入队列                node.prev = t;                if (compareAndSetTail(t, node)) {                    t.next = node;                    return t;                }            }        }    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
4.acuqireQueued方法,进行访问控制。只有一个线程能够获取锁,其他均必须等待。每个线程均可以自省观察,当前驱为头结点并原子性获得状态,则可以运行    final boolean acquireQueued(final Node node, int arg) {        boolean failed = true;        try {            boolean interrupted = false;            for (;;) {                final Node p = node.predecessor();  //获取节点前驱,若为null报错                //若前驱为头结点且能获取状态,代表当前节点能够占有锁                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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
5.release方法,表示将资源释放,即将锁释放    public final boolean release(int arg) {        if (tryRelease(arg)) {            Node h = head;            if (h != null && h.waitStatus != 0) //waitStatus为等待状态                unparkSuccessor(h); //唤醒当前节点的后继节点所包含的线程            return true;        }        return false;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
6.tryRelease方法,一般被子类重写,用于释放状态。参数为所要释放的状态        protected boolean tryRelease(int arg) {        throw new UnsupportedOperationException();    }
  • 1
  • 2
  • 3
  • 4
7.unparkSuccessor方法,唤醒当前节点的后继节点所包含的线程    private void unparkSuccessor(Node node) {        int ws = node.waitStatus;        if (ws < 0)     //若小于0,则将状态设为0            compareAndSetWaitStatus(node, ws, 0);        /*        获取当前节点的后继节点,如果满足状态,那么进行唤醒操作          如果没有满足状态,从尾部开始找寻符合要求的节点并将其唤醒          */        Node s = node.next;        if (s == null || s.waitStatus > 0) { //大于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);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

回顾整个资源的获取和释放过程: 
在获取时,维护了一个sync队列,每个节点都是一个线程在进行自旋,而依据就是自己是否是首节点的后继并且能够获取资源; 
在释放时,仅仅需要将资源还回去,然后通知一下后继节点并将其唤醒。 
这里需要注意,队列的维护(首节点的更换)是依靠消费者(获取时)来完成的,也就是说在满足了自旋退出的条件时的一刻,这个节点就会被设置成为首节点。

8.acquireShared方法,用于共享状态的获取    public final void acquireShared(int arg) {        if (tryAcquireShared(arg) < 0)              doAcquireShared(arg);   //获取失败则进入该方法    }
  • 1
  • 2
  • 3
  • 4
  • 5
9.tryAcquireShared方法,一般被子类重写,用于在共享的模式下获取状态。若返回附属表示未获取到。    protected int tryAcquireShared(int arg) {        throw new UnsupportedOperationException();    }
  • 1
  • 2
  • 3
  • 4
10.doAcquireShared方法,用于共享模式获取。    private void doAcquireShared(int arg) {        final Node node = addWaiter(Node.SHARED);//首先将获取失败的节点加入到sync队列中        boolean failed = true;        try {            boolean interrupted = false;            for (;;) {                final Node p = node.predecessor();                if (p == head) {                    int r = tryAcquireShared(arg);                    if (r >= 0) { //如果当前节点的前驱节点是头结点并且获取共享状态成功                        setHeadAndPropagate(node, r);                        p.next = null; // help GC                        if (interrupted)                            selfInterrupt();                        failed = false;                        return;                    }                }                //如果共享状态获取成功之后会判断后继节点是否是共享模式。                //如果是共享模式,那么就直接对其进行唤醒操作,也就是同时激发多个线程并发的运行。                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    interrupted = true;            }        } finally {            if (failed)                cancelAcquire(node);        }    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

image

11.releaseShared方法,用于共享模式下的锁释放public final boolean releaseShared(int arg) {        if (tryReleaseShared(arg)) {            doReleaseShared();              return true;        }        return false;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
12.tryReleaseShared方法,子类一般重写该方法,用于共享模式下的释放资源    protected boolean tryRelease(int arg) {        throw new UnsupportedOperationException();    }
  • 1
  • 2
  • 3
  • 4
13.唤醒其后继结点    private void doReleaseShared() {        for (;;) {            Node h = head;            if (h != null && h != tail) {                int ws = h.waitStatus;                if (ws == Node.SIGNAL) {                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))                        continue;            // loop to recheck cases                    unparkSuccessor(h);                }                else if (ws == 0 &&                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))                    continue;                // loop on failed CAS            }            if (h == head)                   // loop if head changed                break;        }    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
14.setExclusiveOwnerThread方法,继承自AbstractOwnableSynchronizer,表示设置当前独占锁的线程。若为null表示没有线程拥有访问权限    protected final void setExclusiveOwnerThread(Thread thread) {        exclusiveOwnerThread = thread;    }
原创粉丝点击