JDK1.8源码阅读与翻译:CyclicBarrier

/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A synchronization aid that allows a set of threads to all wait for
 * each other to reach a common barrier point.  CyclicBarriers are
 * useful in programs involving a fixed sized party of threads that
 * must occasionally wait for each other. The barrier is called
 * <em>cyclic</em> because it can be re-used after the waiting threads
 * are released.
 * CyclicBarrier是一个同步辅助类,允许一组线程全部等待彼此到达一个公共屏障点。
 * CyclicBarriers在涉及固定数量的一批线程必须偶尔等待彼此的程序中很有用。被称
 * 为cyclic(循环)barrier(屏障)是因为它可以在释放等待线程后继续重复使用。
 *
 * <p>A {@code CyclicBarrier} supports an optional {@link Runnable} command
 * that is run once per barrier point, after the last thread in the party
 * arrives, but before any threads are released.
 * This <em>barrier action</em> is useful
 * for updating shared-state before any of the parties continue.
 * CyclicBarrier支持一个可选的命令(Runnable),该命令在每个屏障点运行一次,
 * 该命令执行的时机在在同批次的最后一个线程到达屏障点之后,在任意线程释放之前。
 * 这个屏障操作对于任何一方(线程)继续之前,对于更新共享状态有用。
 *
 * <p><b>Sample usage:</b> Here is an example of using a barrier in a
 * parallel decomposition design:
 *
 *  <pre> {@code
 * class Solver {
 *   final int N;
 *   final float[][] data;
 *   final CyclicBarrier barrier;
 *
 *   class Worker implements Runnable {
 *     int myRow;
 *     Worker(int row) { myRow = row; }
 *     public void run() {
 *       while (!done()) {
 *         processRow(myRow);
 *
 *         try {
 *           barrier.await();
 *         } catch (InterruptedException ex) {
 *           return;
 *         } catch (BrokenBarrierException ex) {
 *           return;
 *         }
 *       }
 *     }
 *   }
 *
 *   public Solver(float[][] matrix) {
 *     data = matrix;
 *     N = matrix.length;
 *     Runnable barrierAction =
 *       new Runnable() { public void run() { mergeRows(...); }};
 *     barrier = new CyclicBarrier(N, barrierAction);
 *
 *     List<Thread> threads = new ArrayList<Thread>(N);
 *     for (int i = 0; i < N; i++) {
 *       Thread thread = new Thread(new Worker(i));
 *       threads.add(thread);
 *       thread.start();
 *     }
 *
 *     // wait until done
 *     for (Thread thread : threads)
 *       thread.join();
 *   }
 * }}</pre>
 *
 * Here, each worker thread processes a row of the matrix then waits at the
 * barrier until all rows have been processed. When all rows are processed
 * the supplied {@link Runnable} barrier action is executed and merges the
 * rows. If the merger
 * determines that a solution has been found then {@code done()} will return
 * {@code true} and each worker will terminate.
 * 以上代码中,每个worker线程处理二维数组中的一行,然后在屏障处等待直到所有行均被处理。当所
 * 有行都被处理后,将执行屏障操作Runnable,合并这些行。如果这个Runnable线程确定问题解决,
 * 则done()将返回true,从而每个worker线程退出while循环,执行结束。
 *
 * <p>If the barrier action does not rely on the parties being suspended when
 * it is executed, then any of the threads in the party could execute that
 * action when it is released. To facilitate this, each invocation of
 * {@link #await} returns the arrival index of that thread at the barrier.
 * You can then choose which thread should execute the barrier action, for
 * example:
 * 如果屏障操作执行时不依赖被挂起的任何线程,则任何线程都可以在释放后执行这个屏障操作。为了
 * 实现这一点,每次await()调用都会返回该线程到达屏障的序号。你可以选择具体哪个线程来执行屏
 * 障操作。例如下边是让序号为0的线程执行指定操作:
 *  <pre> {@code
 * if (barrier.await() == 0) {
 *   // log the completion of this iteration
 * }}</pre>
 *
 * <p>The {@code CyclicBarrier} uses an all-or-none breakage model
 * for failed synchronization attempts: If a thread leaves a barrier
 * point prematurely because of interruption, failure, or timeout, all
 * other threads waiting at that barrier point will also leave
 * abnormally via {@link BrokenBarrierException} (or
 * {@link InterruptedException} if they too were interrupted at about
 * the same time).
 * CyclicBarrier为失败的同步尝试应用俱荣俱损模型:如果一个线程由于中断,错误或超时离开屏障,
 * 所有其他在屏障处等待的线程都将由于BrokenBarrierException异常离开屏障点(或是由于
 * InterruptedException被同时中断)
 *
 * <p>Memory consistency effects: Actions in a thread prior to calling
 * {@code await()}
 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
 * actions that are part of the barrier action, which in turn
 * <i>happen-before</i> actions following a successful return from the
 * corresponding {@code await()} in other threads.
 * 内存一致效果:先前调用await()的线程的动作,happen-before(先于发生)屏障操作的动作,
 * 而屏障操作的动作先于发生其他线程从await()返回。
 *
 * @since 1.5
 * @see CountDownLatch
 *
 * @author Doug Lea
 */
public class CyclicBarrier {
  /**
   * Each use of the barrier is represented as a generation instance.
   * The generation changes whenever the barrier is tripped, or
   * is reset. There can be many generations associated with threads
   * using the barrier - due to the non-deterministic way the lock
   * may be allocated to waiting threads - but only one of these
   * can be active at a time (the one to which {@code count} applies)
   * and all the rest are either broken or tripped.
   * There need not be an active generation if there has been a break
   * but no subsequent reset.
   * 每次(CyclicBarrier可重用,指每一轮的使用)对屏障的使用用一个Generation实例
   * 来表示。每当屏障被跳过或重置时都会替换这个generation属性。使用屏障的线程可以有
   * 很多代 - 由于锁是用非确定方式分配给等待线程的 - 但是同一时间只有一个generation
   * (一代)会被激活(应用当前count的),其他所有的要么破坏要么跳过屏障。如果有中断
   * 但没有后续的重置,则不需要活动的generation。
   */
  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 */
  /** 标识CyclicBarrier当前代 */
  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.
   * 未到达屏障的线程数量。每一代都会从parties的值减到0。在生成新一代或被破坏时
   * 重置为parties的值。
   */
  private int count;

  /**
   * Updates state on barrier trip and wakes up everyone.
   * Called only while holding lock.
   * 越过屏障时更新状态并唤醒所有线程。
   * 只在持有锁后才调用。
   */
  private void nextGeneration() {
    // signal completion of last generation
    // 唤醒当前一代的所有线程
    trip.signalAll();
    // set up next generation
    // 设置新一代的值
    count = parties;
    generation = new Generation();
  }

  /**
   * Sets current barrier generation as broken and wakes up everyone.
   * Called only while holding lock.
   * 将当前的屏障设置为被破坏并唤醒所有线程。
   * 只在持有锁后才调用。
   */
  private void breakBarrier() {
    generation.broken = true;
    count = parties;
    trip.signalAll();
  }

  /**
   * Main barrier code, covering the various policies.
   * 屏障的主要代码,涵盖各种策略。
   */
  private int dowait(boolean timed, long nanos)
      throws InterruptedException, BrokenBarrierException,
      TimeoutException {
    // CyclicBarrier比CountDownLatch复杂,这里引入了可重入锁来保证线程安全。
    // 其实本类直接利用了ReentrantLock的非公平锁来实现。
    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;// 对count做递减
      if (index == 0) {  // tripped 减到0,越过屏障了
        boolean ranAction = false;
        try {
          final Runnable command = barrierCommand;
          if (command != null)
            // 虽然是Runnable,但并未起新线程,这里直接执行的run
            command.run();
          ranAction = true;
          nextGeneration();
          return 0;
        } finally {
          if (!ranAction)
            // 异常情况,将本代标记为被破坏,唤醒所有线程
            breakBarrier();
        }
      }

      // loop until tripped, broken, interrupted, or timed out
      // 持续循环,直到屏障被越过、破坏、线程中断或超时
      for (;;) {
        try {
          if (!timed)
            // 不限时等待,AQS里面调用了LockSupport.park
            trip.await();
          else if (nanos > 0L)
            // 限时等待,AQS里面调用了LockSupport.parkNanos
            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();
    }
  }

  /**
   * Creates a new {@code CyclicBarrier} that will trip when the
   * given number of parties (threads) are waiting upon it, and which
   * will execute the given barrier action when the barrier is tripped,
   * performed by the last thread entering the barrier.
   * 创建一个新的CyclicBarrier,屏障会在等待线程数达到指定的parties数值时跳过,
   * 跳过时会执行指定的屏障操作,该操作被最后一个到达屏障的线程执行(count减到0时)。
   *
   * @param parties the number of threads that must invoke {@link #await}
   *        before the barrier is tripped
   * @param barrierAction the command to execute when the barrier is
   *        tripped, or {@code null} if there is no action
   * @throws IllegalArgumentException if {@code parties} is less than 1
   */
  public CyclicBarrier(int parties, Runnable barrierAction) {
    if (parties <= 0) throw new IllegalArgumentException();
    this.parties = parties;
    this.count = parties;
    this.barrierCommand = barrierAction;
  }

  /**
   * Creates a new {@code CyclicBarrier} that will trip when the
   * given number of parties (threads) are waiting upon it, and
   * does not perform a predefined action when the barrier is tripped.
   * 创建一个新的CyclicBarrier,屏障会在等待线程数达到指定的parties数值时跳过,
   * 跳过时不执行屏障操作。
   *
   * @param parties the number of threads that must invoke {@link #await}
   *        before the barrier is tripped
   * @throws IllegalArgumentException if {@code parties} is less than 1
   */
  public CyclicBarrier(int parties) {
    this(parties, null);
  }

  /**
   * Returns the number of parties required to trip this barrier.
   * 返回越过屏障需要的线程数。
   *
   * @return the number of parties required to trip this barrier
   */
  public int getParties() {
    return parties;
  }

  /**
   * Waits until all {@linkplain #getParties parties} have invoked
   * {@code await} on this barrier.
   * 一直等待,直到指定数量(parties)的线程调用过await。
   *
   * <p>If the current thread is not the last to arrive then it is
   * disabled for thread scheduling purposes and lies dormant until
   * one of the following things happens:
   * 如果当前线程不是最后一个调用await的,那它将禁止再进行线程调度并在以下任意情况
   * 发生之前都处于休眠状态:
   * <ul>
   * <li>The last thread arrives; or
   * <li>Some other thread {@linkplain Thread#interrupt interrupts}
   * the current thread; or
   * <li>Some other thread {@linkplain Thread#interrupt interrupts}
   * one of the other waiting threads; or
   * <li>Some other thread times out while waiting for barrier; or
   * <li>Some other thread invokes {@link #reset} on this barrier.
   * </ul>
   * 最后一个线程调用了await;其他线程中断了当前线程;其他线程中断了已处于等待状态
   * 的线程;等待中的线程超时;其他线程调用了屏障的reset
   *
   * <p>If the current thread:
   * <ul>
   * <li>has its interrupted status set on entry to this method; or
   * <li>is {@linkplain Thread#interrupt interrupted} while waiting
   * </ul>
   * then {@link InterruptedException} is thrown and the current thread's
   * interrupted status is cleared.
   * 如果当前线程在进入本方法之前就设置了中断状态,或在等待时被中断,那么将会抛出
   * InterruptedException并清理掉当前线程的中断状态。
   *
   * <p>If the barrier is {@link #reset} while any thread is waiting,
   * or if the barrier {@linkplain #isBroken is broken} when
   * {@code await} is invoked, or while any thread is waiting, then
   * {@link BrokenBarrierException} is thrown.
   * 如果在任何线程等待过程中调用了屏障的reset方法,或者await在调用时或任意线程等待
   * 中屏障的isBroken为true,则会抛出BrokenBarrierException
   *
   * <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting,
   * then all other waiting threads will throw
   * {@link BrokenBarrierException} and the barrier is placed in the broken
   * state.
   * 如果任意线程在等待时被中断,则其他所有的等待线程都将抛出BrokenBarrierException,
   * 且屏障的状态被置为被破坏。
   *
   * <p>If the current thread is the last thread to arrive, and a
   * non-null barrier action was supplied in the constructor, then the
   * current thread runs the action before allowing the other threads to
   * continue.
   * If an exception occurs during the barrier action then that exception
   * will be propagated in the current thread and the barrier is placed in
   * the broken state.
   * 如果当前线程是最后一个调用await的,并且屏障创建时传入了非null的屏障操作,那么当前
   * 线程将会在唤醒其他线程前执行这个操作。如果在屏障操作执行中发生了异常,这个异常将会抛
   * 出到当前线程且屏障状态被置为被破坏。
   *
   * @return the arrival index of the current thread, where index
   *         {@code getParties() - 1} indicates the first
   *         to arrive and zero indicates the last to arrive
   * @throws InterruptedException if the current thread was interrupted
   *         while waiting
   * @throws BrokenBarrierException if <em>another</em> thread was
   *         interrupted or timed out while the current thread was
   *         waiting, or the barrier was reset, or the barrier was
   *         broken when {@code await} was called, or the barrier
   *         action (if present) failed due to an exception
   */
  public int await() throws InterruptedException, BrokenBarrierException {
    try {
      return dowait(false, 0L);
    } catch (TimeoutException toe) {
      throw new Error(toe); // cannot happen
    }
  }

  /**
   * Waits until all {@linkplain #getParties parties} have invoked
   * {@code await} on this barrier, or the specified waiting time elapses.
   *
   * <p>If the current thread is not the last to arrive then it is
   * disabled for thread scheduling purposes and lies dormant until
   * one of the following things happens:
   * <ul>
   * <li>The last thread arrives; or
   * <li>The specified timeout elapses; or
   * <li>Some other thread {@linkplain Thread#interrupt interrupts}
   * the current thread; or
   * <li>Some other thread {@linkplain Thread#interrupt interrupts}
   * one of the other waiting threads; or
   * <li>Some other thread times out while waiting for barrier; or
   * <li>Some other thread invokes {@link #reset} on this barrier.
   * </ul>
   *
   * <p>If the current thread:
   * <ul>
   * <li>has its interrupted status set on entry to this method; or
   * <li>is {@linkplain Thread#interrupt interrupted} while waiting
   * </ul>
   * then {@link InterruptedException} is thrown and the current thread's
   * interrupted status is cleared.
   *
   * <p>If the specified waiting time elapses then {@link TimeoutException}
   * is thrown. If the time is less than or equal to zero, the
   * method will not wait at all.
   *
   * <p>If the barrier is {@link #reset} while any thread is waiting,
   * or if the barrier {@linkplain #isBroken is broken} when
   * {@code await} is invoked, or while any thread is waiting, then
   * {@link BrokenBarrierException} is thrown.
   *
   * <p>If any thread is {@linkplain Thread#interrupt interrupted} while
   * waiting, then all other waiting threads will throw {@link
   * BrokenBarrierException} and the barrier is placed in the broken
   * state.
   *
   * <p>If the current thread is the last thread to arrive, and a
   * non-null barrier action was supplied in the constructor, then the
   * current thread runs the action before allowing the other threads to
   * continue.
   * If an exception occurs during the barrier action then that exception
   * will be propagated in the current thread and the barrier is placed in
   * the broken state.
   *
   * @param timeout the time to wait for the barrier
   * @param unit the time unit of the timeout parameter
   * @return the arrival index of the current thread, where index
   *         {@code getParties() - 1} indicates the first
   *         to arrive and zero indicates the last to arrive
   * @throws InterruptedException if the current thread was interrupted
   *         while waiting
   * @throws TimeoutException if the specified timeout elapses.
   *         In this case the barrier will be broken.
   * @throws BrokenBarrierException if <em>another</em> thread was
   *         interrupted or timed out while the current thread was
   *         waiting, or the barrier was reset, or the barrier was broken
   *         when {@code await} was called, or the barrier action (if
   *         present) failed due to an exception
   */
  public int await(long timeout, TimeUnit unit)
      throws InterruptedException,
      BrokenBarrierException,
      TimeoutException {
    return dowait(true, unit.toNanos(timeout));
  }

  /**
   * Queries if this barrier is in a broken state.
   *
   * @return {@code true} if one or more parties broke out of this
   *         barrier due to interruption or timeout since
   *         construction or the last reset, or a barrier action
   *         failed due to an exception; {@code false} otherwise.
   */
  public boolean isBroken() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
      return generation.broken;
    } finally {
      lock.unlock();
    }
  }

  /**
   * Resets the barrier to its initial state.  If any parties are
   * currently waiting at the barrier, they will return with a
   * {@link BrokenBarrierException}. Note that resets <em>after</em>
   * a breakage has occurred for other reasons can be complicated to
   * carry out; threads need to re-synchronize in some other way,
   * and choose one to perform the reset.  It may be preferable to
   * instead create a new barrier for subsequent use.
   * 重置屏障到初始状态。如果任意线程正在屏障处等待,他们将抛出BrokenBarrierException。
   * 注意在屏障由于其他原因被破坏后进行重置可能会很复杂;这些线程需要用其他方式重新同步,
   * 并选择其中一个执行reset。为后续使用创建一个新的屏障可能是最优的选择。
   */
  public void reset() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
      breakBarrier();   // break the current generation
      nextGeneration(); // start a new generation
    } finally {
      lock.unlock();
    }
  }

  /**
   * Returns the number of parties currently waiting at the barrier.
   * This method is primarily useful for debugging and assertions.
   * 返回正在屏障处等待的线程数量。本方法主要用于调试和断言。
   *
   * @return the number of parties currently blocked in {@link #await}
   */
  public int getNumberWaiting() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
      return parties - count;
    } finally {
      lock.unlock();
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值