11 |
|
import java.util.concurrent.BrokenBarrierException; |
12 |
|
import java.util.concurrent.CountDownLatch; |
13 |
|
import java.util.concurrent.CyclicBarrier; |
14 |
+ |
import java.util.concurrent.ExecutorService; |
15 |
+ |
import java.util.concurrent.Executors; |
16 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
17 |
|
import java.util.concurrent.TimeoutException; |
18 |
|
import java.util.concurrent.atomic.AtomicBoolean; |
19 |
|
import java.util.concurrent.atomic.AtomicInteger; |
462 |
|
assertEquals(0, barrier.getNumberWaiting()); |
463 |
|
} |
464 |
|
} |
465 |
+ |
|
466 |
+ |
/** |
467 |
+ |
* There can be more threads calling await() than parties, as long as each |
468 |
+ |
* task only calls await once and the task count is a multiple of parties. |
469 |
+ |
*/ |
470 |
+ |
public void testMoreTasksThanParties() throws Exception { |
471 |
+ |
final ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
472 |
+ |
final int parties = rnd.nextInt(1, 5); |
473 |
+ |
final int nTasks = rnd.nextInt(1, 5) * parties; |
474 |
+ |
final AtomicInteger tripCount = new AtomicInteger(0); |
475 |
+ |
final AtomicInteger awaitCount = new AtomicInteger(0); |
476 |
+ |
final CyclicBarrier barrier = |
477 |
+ |
new CyclicBarrier(parties, () -> tripCount.getAndIncrement()); |
478 |
+ |
final ExecutorService e = Executors.newFixedThreadPool(nTasks); |
479 |
+ |
final Runnable awaiter = () -> { |
480 |
+ |
try { |
481 |
+ |
if (ThreadLocalRandom.current().nextBoolean()) |
482 |
+ |
barrier.await(); |
483 |
+ |
else |
484 |
+ |
barrier.await(LONG_DELAY_MS, MILLISECONDS); |
485 |
+ |
awaitCount.getAndIncrement(); |
486 |
+ |
} catch (Throwable fail) { threadUnexpectedException(fail); }}; |
487 |
+ |
try (PoolCleaner cleaner = cleaner(e)) { |
488 |
+ |
for (int i = nTasks; i--> 0; ) |
489 |
+ |
e.execute(awaiter); |
490 |
+ |
} |
491 |
+ |
assertEquals(nTasks / parties, tripCount.get()); |
492 |
+ |
assertEquals(nTasks, awaitCount.get()); |
493 |
+ |
assertEquals(0, barrier.getNumberWaiting()); |
494 |
+ |
} |
495 |
|
} |