38 import java.util.concurrent.BrokenBarrierException; |
38 import java.util.concurrent.BrokenBarrierException; |
39 import java.util.concurrent.CountDownLatch; |
39 import java.util.concurrent.CountDownLatch; |
40 import java.util.concurrent.CyclicBarrier; |
40 import java.util.concurrent.CyclicBarrier; |
41 import java.util.concurrent.TimeoutException; |
41 import java.util.concurrent.TimeoutException; |
42 import java.util.concurrent.atomic.AtomicBoolean; |
42 import java.util.concurrent.atomic.AtomicBoolean; |
|
43 import java.util.concurrent.atomic.AtomicInteger; |
43 |
44 |
44 import junit.framework.Test; |
45 import junit.framework.Test; |
45 import junit.framework.TestSuite; |
46 import junit.framework.TestSuite; |
46 |
47 |
47 public class CyclicBarrierTest extends JSR166TestCase { |
48 public class CyclicBarrierTest extends JSR166TestCase { |
48 public static void main(String[] args) { |
49 public static void main(String[] args) { |
49 main(suite(), args); |
50 main(suite(), args); |
50 } |
51 } |
51 public static Test suite() { |
52 public static Test suite() { |
52 return new TestSuite(CyclicBarrierTest.class); |
53 return new TestSuite(CyclicBarrierTest.class); |
53 } |
|
54 |
|
55 private volatile int countAction; |
|
56 private class MyAction implements Runnable { |
|
57 public void run() { ++countAction; } |
|
58 } |
54 } |
59 |
55 |
60 /** |
56 /** |
61 * Spin-waits till the number of waiters == numberOfWaiters. |
57 * Spin-waits till the number of waiters == numberOfWaiters. |
62 */ |
58 */ |
112 |
108 |
113 /** |
109 /** |
114 * The supplied barrier action is run at barrier |
110 * The supplied barrier action is run at barrier |
115 */ |
111 */ |
116 public void testBarrierAction() throws Exception { |
112 public void testBarrierAction() throws Exception { |
117 countAction = 0; |
113 final AtomicInteger count = new AtomicInteger(0); |
118 CyclicBarrier b = new CyclicBarrier(1, new MyAction()); |
114 final Runnable incCount = new Runnable() { public void run() { |
|
115 count.getAndIncrement(); }}; |
|
116 CyclicBarrier b = new CyclicBarrier(1, incCount); |
119 assertEquals(1, b.getParties()); |
117 assertEquals(1, b.getParties()); |
120 assertEquals(0, b.getNumberWaiting()); |
118 assertEquals(0, b.getNumberWaiting()); |
121 b.await(); |
119 b.await(); |
122 b.await(); |
120 b.await(); |
123 assertEquals(0, b.getNumberWaiting()); |
121 assertEquals(0, b.getNumberWaiting()); |
124 assertEquals(2, countAction); |
122 assertEquals(2, count.get()); |
125 } |
123 } |
126 |
124 |
127 /** |
125 /** |
128 * A 2-party/thread barrier triggers after both threads invoke await |
126 * A 2-party/thread barrier triggers after both threads invoke await |
129 */ |
127 */ |