JUC 源码:信号量Semaphore ,倒计时CountDownLatch 与循环栅栏CyclicBarrier

425 阅读4分钟

信号量

信号量用于控制访问共享资源的线程的数量。信号量将资源抽象成许可,维护一个许可池子。获取资源减少许可,释放资源增加许可。池子本身也是一个多线程共享的资源,信号量保证多线程下对池子操作的安全性,通过自旋CAS来保证这一点。

应用场景

  1. N个信号量,控制只能N个线程进入临界区
  2. 1个信号量,当成互斥锁使用

内存一致性效果:

一个线程中调用release之前的操作 happense before 另一个线程后继的acquire之后的操作。

源码

代码比较简单。只摘录其中一个代码。

    final int nonfairTryAcquireShared(int acquires) {
            for (;;) {
                int available = getState();
                int remaining = available - acquires;
                if (remaining < 0 ||
                    compareAndSetState(available, remaining))
                    return remaining;
            }
        }

CountDownLatch

用于一个或多个线程等待,直到其他线程完成了相应的工作 初始化时带有数量count. countdown方法减少count. await方法会阻塞自己,直到count到达0. count一旦降低到0,则无法恢复。如果序号重置count,使用CyclicBarrier

内存一致性效果:

一个线程的countdown之前的操作 happens before 其他线程从await方法返回后的操作

应用场景

  1. count设置为1。用作一个大门,多个线程等待大门打开才可继续执行。另一个线程负责打开大门
  2. count设置为N。一个线程阻塞自己,直到其他N个线程完成了对应的任务,或者对应的任务完成了N次,才可以继续执行。
  3. count设置为N. 主线程将任务分成N部分交给N个线程完成。主线程阻塞自己,直到整个任务完成了才可继续执行。

源码

较为简单,仅摘录一段

    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

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

        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;
            }
        }
    }

CyclicBarrier

CyclicBarrier类似于一个栅栏,N个线程是一个队伍(party)。线程运行到栅栏处阻塞,直到N个线程全部到达栅栏才可继续向前运行。前N-1个线程到达会阻塞,最后一个线程到达栅栏时会绊倒(trip)栅栏。这时候整个队伍中的线程被唤醒继续运行。

内存一致性效果

一个线程调用await()方法之前的动作 happens before 栅栏中的动作(栅栏被绊倒执行的command) happens before 从await()方法返回后执行的动作

应用场景

  1. 类似登山队伍,多个线程首先在栅栏前集合,全体到齐才可以打开栅栏允许同行。

属性

CyclicBarrier中,通过ReentrantLock来保证并发安全性。

线程阻塞在条件变量上。parties代表线程队伍的线程个数,generation表示队伍的代数。因为栅栏是可以重复使用的。用generation来区分不同的栅栏。count表示还未到达栅栏处的线程数量。

    private static class Generation {
        boolean broken = false;
    }

    /** The lock for guarding barrier entry */
    private final ReentrantLock lock = new ReentrantLock();
    /** Condition to wait on until tripped */
    private final Condition trip = lock.newCondition();
    /** The number of parties */
    private final int parties;
    /* The command to run when tripped */
    private final Runnable barrierCommand;
    /** The current generation */
    private Generation generation = new Generation();

    /**
     * Number of parties still waiting. Counts down from parties to 0
     * on each generation.  It is reset to parties on each new
     * generation or when broken.
     */
    private int count;

await

当线程到达栅栏处,调用await方法等待队伍中的其他线程

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

该方法会调用dowait() 首先获取锁,然后保存栅栏分代的快照g。 然后将等待的线程数量count--。 如果当前线程是队伍中最后一个到达的线程,会执行barrierCommand方法,调用nextgeneration方法来唤醒队伍中的线程并将栅栏进入下一代。 如果不是最后一个到达的线程,阻塞在条件变量上,等待唤醒。

private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Generation g = generation;

            if (g.broken)
                throw new BrokenBarrierException();

            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

            int index = --count;
            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) {
                    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();
                    }
                }

                if (g.broken)
                    throw new BrokenBarrierException();

                if (g != generation)
                    return index;

                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }
 private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();
        // set up next generation
        count = parties;
        generation = new Generation();
    }

reset

会导致当前栅栏损坏(breakBarrier会唤醒等待队列中的线程),栅栏进入下一代

   public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }