转载

Java中常见的并发组件

Rlock在构造的时候传入一个标记是否为fair的boolean,表示该锁在释放的时候是否偏向将权限交给等待时间最长的线程,否则对获取锁的顺序不做任何保证。公平锁会带来很大的性能损耗,但是优点是获取锁的时间方差较小,而且不会有饿死的风险.

调用Rlock的tryLock()方法的时候不会关心是否设置了fair标记,只要此时没有线程持有锁,那么就可以获取到锁,不用关心正在waiting锁的那些线程。tryLock()继承自Lock类,如果此时不能获取到锁,会直接返回false,不会阻塞线程的运行。

RLock的内部类Sync继承了AQS类,通过这个类实现lock的语义。其中用Sync的成员state表示此时持有锁的线程数(可重入)。Sync的子类包含是否fair两个版本,默认为非fair.

Rlock中lock()与lockInterruptibly()的区别在于线程阻塞在等待锁的时候是否响应中断。如果有其他线程中断此线程,获取此线程获取到锁,lockInterruptibly()调用结束,线程停止阻塞。

tryLock()方法的通过调用sync.nonfairTryAcquire(1)来实现。因为这个方法只是简单判断是否有其他线程持有锁,有的话直接返回false,否则如果state=0(没有线程持有锁)或者current == getExclusiveOwnerThread()(就是本线程持有),直接修改state状态,再返回true即可。代码如下:

final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
复制代码

下面主要看lock方法的实现。lock()方法通过调用sync.lock()实现。先看fair的情况。 (R)lock() -> (R)sync.lock() -> (A)acquire(1) -> (A)

public final void acquire(int arg) {
        //如果tryAcquire成功,后面自然不用执行,否则排队(所以线程在队列中只会有一个节点)
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
复制代码

我们猜测,acquireQueued中线程会进入阻塞状态。先一步步看,第一步是addWaiter;

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;
    }
复制代码

除了注意要用cas的方式将Node塞入到链表的末尾,其他貌似没什么要深入的,先跳过。这一步结束以后我们成功创建了一个代表本线程的Node到队列尾部,然后呢?

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);
        }
    }
复制代码

在acquire方法中,我们已经见到过一次tryAcquire()方法,我们当时是假设了它为false的情况,然后继续往后面走,现在又遇到,看来有必要看一下它的实现。出乎意料的是,tryAcquire()是AQS里面一个抽象方法,需要我们自己实现。上面从tryLock()开始,我们已经看到一个nonfairTryAcquire()方法了,从名字上看这个方法是不管是否公平,去获取一次锁,成功true,失败false,那么tryAcquire()如何实现呢?

NonfairSync下的tryAcquire实现

protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
复制代码

FairSync下的tryAcquire实现

protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                //这儿就是判断是否fair的关键代码,先判断是是否在排队呢
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
复制代码

虽然lock()方法都走到了Sync类下面的tryAcquire方法,但是看得出来不同的Sync子类对这个方法的实现不相同。那还是回到acquireQueued方法中吧,

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())
                    //可以直接把interruptedException抛出来,这就是lockInterupt()方法的做法
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
复制代码

先看这个方法

/**
     * Checks and updates status for a node that failed to acquire.
     * Returns true if thread should block. This is the main signal
     * control in all acquire loops.  Requires that pred == node.prev.
     *
     * @param pred node's predecessor holding status
     * @param node the node
     * @return {@code true} if thread should block
     */
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }
复制代码

这个方法的目的主要是两个

  1. 告诉上一个节点,release锁的时候,需要通知我(processor的status设置为Singal)
  2. 把cancelled的线程占用的节点取消掉

做完了上面的准备工作,这个线程就可以安心“休息”了。

private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        //注意,这里检测了线程是否被interrupted。如果此时捕获到中断的信息,需要在上面代码中“抛出”此中断,让其他实现中断响应策略的代码,能够获知这一状态。
        return Thread.interrupted();
    }
复制代码

现在线程算是进入阻塞了。什么时候唤醒? 看unLock()的代码:

public void unlock() {
        sync.release(1);
    }
复制代码

代码链路是(R)unlock() -> (A)release() -> (R)tryRelease()

protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }
复制代码

这个基本上上tryAcquire相反的动作。如果release成功了,就把队列第一个节点的线程释放了,代码:

public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        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);
    }
复制代码

synchronized

synchronized是什么?

CountDownLatch

CDL用于一个线程等待其他线程上面一系列操作的完成。在初始化的时候指定一个count,每次操作完成调用countDown()使count减少。当count减少到0的时候,所有阻塞在await()方法上面的线程都将立即执行。注意count不能被重置,如果想重置,建议使用CyclicBarrier。

CDL能帮助保证内存一致性原则:一个线程中,调用countdown()方法之前的动作一定发生在其他线程await()方法返回之前。

和RLock的实现一样,CDL内部也继承了AQS类,即Sync类。CDL await()流程分析: (C)await() -> (A)acquireSharedInterruptibly

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
复制代码

和RLock类似,先尝试用用tryAcquireShared获取一下锁

protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }
复制代码

在初始化CDL的时候,传入的state是指定的count数,所以tryAcquireShared这个方法就是先看state是否降到零,如果降到零,就不用阻塞,往下执行了,否则,会调用AQS中的doAcquireSharedInterruptibly方法:

private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
复制代码

我们发现这个方法和上文提到的acquireQueued方法基本类似

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())
                    //可以直接把interruptedException抛出来,这就是lockInterupt()方法的做法
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
复制代码

区别在于当此节点的前驱节点为head节点时(意思是自己现在排第一),调用的是tryAcquireShared方法,比tryAcquire多了一个shared。tryAcquire方法的实现一般都比较简单,其实和tryAcquire意思差不多,这是这个state复杂了一点,其他地方除了将节点status设置为SHARED,和上面的就没什么区别了,后面是同样的阻塞逻辑。

然后看countdown()方法。

public void countDown() {
        sync.releaseShared(1);
    }
复制代码

再进到AQS中去

public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
复制代码

CDL中,将state将1,直到为0的时候返回true,此时将线程释放

protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
复制代码
private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        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;
        }
    }
复制代码

Semaphore

S内部为了一些许可,一个线程在获取不到许可的时候会被阻塞,直到分配一个许可给它。释放许可的时候会增加S中的许可,因此,S通常用于控制线程访问资源的数目。S在初始化的时候可以只有一个许可,也就是binary Semaphore,它的作用和lock不同, 因为lock需要本线程自己释放锁,而bs没有这个要求。

Semaphore也分是否公平,含义与RLock一样。

Semaphore内部也实现了AQS的一个子类Snyc.Sync的初始状态(state)为permit数目,表示available的permit数目。先看S的acquire方法:

//注意,semaphore的acquire默认是可以中断的,如果要不中断可以调用acquireUninterruptibly()
public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
复制代码
public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
复制代码

看上去和RLock很像,acquire的时候先try一下,如果成功了最好,否则

private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
复制代码

这个和CDL很像,都是SHARED模式的节点。

从上面几个例子可以看出,要想自定义并发组件,需要做几个事情

  1. 内部继承AQS类,这个类用于提供排队,阻塞的功能
  2. 并发组件如果需要同步,先通过try(state)试一下能不能拿到锁,试成功了万事大吉,线程继续执行。如果没有试成功,通过AQS将这个线程加入到队列中,同时阻塞它的执行。
  3. 并发组件如果想要释放锁,先tryRelease将AQS的state等信息修改,比如降低重入数,修改到我们想要的结果(比如RLock中为0,CDL中降到0),就会通过AQS将节点释放,同时取消线程的阻塞。

大部分定制逻辑在于我们什么时候需要去阻塞线程(插入节点),即我们什么时候需要让try返回false,即比如getState不为0? 同理,我们什么时候需要让getState为0?

我们怎么去实现一个同步工具类?

public class MyThreadSyncUtil {
    private Sync sync;
    class Sync extends AQS {
        booleean tryAcquire();
    }
    
    //会阻塞,还可以区分是否响应中断,区别在于调用sync中响应中断的acquire,区别是此时park完线程以后判断是否抛出intrupted异常
    public void acquire() {
        sync.acquire(); // -> 这里面会用到我们刚刚实现的try,try成功就返回,否则将节点加入到队列
    }
    //直接返回
    public boolean tryAcquire(){
        sync.tryAcquire();
    }
}
复制代码

CyclicBarrier

CB使用的场景是有一系列线程互相等待对方完成任务以后继续执行后面的任务。cyclic意思是指它在线程释放以后可以重复使用。CB支持传入一个Runnable,表示当所有线程完成任务(但还没有释放)的时候执行一下。

每个线程在执行完自己的任务之后,调用cyclicBarrier.await()方法,并阻塞至所有任务完成。await代码为:

public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }
复制代码

其中主要代码为dowait:

private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Generation g = generation;
            //如果barrier被破坏,直接抛出异常结束
            if (g.broken)
                throw new BrokenBarrierException();

            //如果这个线程中途被中断,会中断barrier
            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

            int index = --count;
            //最后一个执行的线程需要执行以下barrierCommand
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    final Runnable command = barrierCommand;
                    if (command != null)
                        command.run();
                    ranAction = true;
                    nextGeneration();
                    return 0;
                } finally {
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) {
                try {
                    if (!timed)
                    //一般情况下会阻塞在这里
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    //阻塞的时候如果被中断,先结束barrier再抛出异常
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // We're about to finish waiting even if we had not
                        // been interrupted, so this interrupt is deemed to
                        // "belong" to subsequent execution.
                        Thread.currentThread().interrupt();
                    }
                }
                //有可能中途被唤醒(因为broken),判断出错以后抛出异常
                if (g.broken)
                    throw new BrokenBarrierException();
                //有可能更新到下一代
                if (g != generation)
                    return index;

                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }
复制代码

breakBarrier的代码是

private void breakBarrier() {
        //broken这个状态属于generation
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }
复制代码
原文  https://juejin.im/post/5e674831f265da57701444bc
正文到此结束
Loading...