/** * 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. */ privatestaticclassGeneration { booleanbroken=false; }
3 字段
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** The lock for guarding barrier entry */ privatefinalReentrantLocklock=newReentrantLock(); /** Condition to wait on until tripped */ privatefinalConditiontrip= lock.newCondition(); /** The number of parties */ privatefinalint parties; /* The command to run when tripped */ privatefinal Runnable barrierCommand; /** The current generation */ privateGenerationgeneration=newGeneration();
/** * 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. */ privateint count;
/** * 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. * * @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 */ publicCyclicBarrier(int parties) { this(parties, null); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * 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. * * @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 */ publicCyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) thrownewIllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; }
/** * Waits until all {@linkplain #getParties parties} have invoked * {@code await} on this barrier. * * <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>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 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. * * @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 */ publicintawait()throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { thrownewError(toe); //cannot happen } }
//阻塞当前线程直至被中断,打断或者超时 //loop until tripped, broken, interrupted, or timed out for (;;) { try { //如果不允许超时,将当前线程直接挂起,阻塞在条件对象trip的condition queue(ConditionObject中维护的等待队列)中 if (!timed) trip.await(); //如果允许超时,阻塞在条件对象trip的condition queue中一段时间 elseif (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(); } }
//如果Barrier被打断,则抛出BrokenBarrierException异常 if (g.broken) thrownewBrokenBarrierException();
//意味着调用await时处于上一个生命周期,而此时却进入了下一个生命周期中 if (g != generation) return index;
/** * Updates state on barrier trip and wakes up everyone. * Called only while holding lock. */ privatevoidnextGeneration() { //signal completion of last generation //唤醒所有阻塞在condition queue中的线程,即那些阻塞在await方法上的线程 trip.signalAll(); //set up next generation //这就是CyclicBarrier可重用的原因 count = parties; //重新生成Generation generation = newGeneration(); }
4.3 isBroken
检查当前Barrier生命周期是否有效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * 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. */ publicbooleanisBroken() { finalReentrantLocklock=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. */ publicvoidreset() { finalReentrantLocklock=this.lock; lock.lock(); try { breakBarrier(); //break the current generation nextGeneration(); //start a new generation } finally { lock.unlock(); } }
4.5 getNumberWaiting
检查有多少个线程阻塞在await方法的调用中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * 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} */ publicintgetNumberWaiting() { finalReentrantLocklock=this.lock; lock.lock(); try { return parties - count; } finally { lock.unlock(); } }