1   package com.atlassian.util.concurrent;
2   
3   import static com.atlassian.util.concurrent.Util.pause;
4   import static org.junit.Assert.assertEquals;
5   import static org.junit.Assert.assertFalse;
6   import static org.junit.Assert.assertTrue;
7   
8   import org.junit.Test;
9   
10  import java.util.concurrent.atomic.AtomicInteger;
11  
12  public class PhasedLatchTest {
13      @Test public void phases() throws Exception {
14          final PhasedLatch latch = new PhasedLatch();
15          final AtomicInteger count = new AtomicInteger();
16          final Thread client = new Thread(new Runnable() {
17              public void run() {
18                  try {
19                      while (true) {
20                          latch.awaitPhase(latch.getPhase());
21                          count.getAndIncrement();
22                      }
23                  }
24                  catch (final InterruptedException ignore) {}
25              }
26          });
27          client.start();
28  
29          final Thread client2 = new Thread(new Runnable() {
30              public void run() {
31                  try {
32                      while (true) {
33                          latch.await();
34                          count.getAndIncrement();
35                      }
36                  }
37                  catch (final InterruptedException ignore) {}
38              }
39          });
40          client2.start();
41  
42          assertEquals(0, count.get());
43          pause();
44          assertEquals(0, count.get());
45          latch.release();
46          pause();
47          assertEquals(2, count.get());
48          latch.release();
49          pause();
50          assertEquals(4, count.get());
51          latch.release();
52          pause();
53          assertEquals(6, count.get());
54  
55          latch.release();
56  
57          client.interrupt();
58      }
59  
60      @Test public void phaseComparator() throws Exception {
61          final PhasedLatch.PhaseComparator comparator = new PhasedLatch.PhaseComparator();
62          assertTrue(comparator.isPassed(1, 0));
63          assertFalse(comparator.isPassed(1, 1));
64          assertFalse(comparator.isPassed(1, 2));
65      }
66  
67      @Test public void phaseComparatorAtMaxValue() throws Exception {
68          final PhasedLatch.PhaseComparator comparator = new PhasedLatch.PhaseComparator();
69          assertTrue(comparator.isPassed(Integer.MAX_VALUE, Integer.MAX_VALUE - 1));
70          assertFalse(comparator.isPassed(Integer.MAX_VALUE, Integer.MAX_VALUE));
71          assertFalse(comparator.isPassed(Integer.MAX_VALUE, Integer.MAX_VALUE + 1));
72      }
73  }