View Javadoc

1   package net.sf.ehcache.util;
2   
3   import org.junit.Test;
4   
5   import java.util.concurrent.ConcurrentHashMap;
6   import java.util.concurrent.ConcurrentMap;
7   import java.util.concurrent.TimeUnit;
8   import java.util.concurrent.atomic.AtomicBoolean;
9   import java.util.concurrent.atomic.AtomicLong;
10  
11  import static org.hamcrest.CoreMatchers.*;
12  import static org.junit.Assert.assertThat;
13  
14  /***
15   * @author Alex Snaps
16   */
17  public class TimestamperTest {
18  
19      public static final int THREADS  = 12;
20      public static final int DURATION = 30;
21  
22      @Test
23      public void testNext() throws Exception {
24          final AtomicBoolean stopped = new AtomicBoolean(false);
25          final ConcurrentMap<Long, Integer> values = new ConcurrentHashMap<Long, Integer>();
26          final AtomicLong errors = new AtomicLong();
27          final AtomicLong totalRuns = new AtomicLong();
28          Thread[] threads = new Thread[THREADS];
29          for(int i =0; i < THREADS; i++) {
30              threads[i] = new Thread() {
31  
32                  long runs;
33  
34                  @Override
35                  public void run() {
36                      while (!stopped.get()) {
37                          Timestamper.next();
38                          ++runs;
39  //                        if(values.putIfAbsent(Timestamper.next(), 0) != null) {
40  //                            errors.incrementAndGet();
41  //                        }
42                      }
43                      totalRuns.addAndGet(runs);
44                  }
45              };
46          }
47          for (Thread thread : threads) {
48              thread.start();
49          }
50          Thread.sleep(TimeUnit.SECONDS.toMillis(DURATION));
51          stopped.set(true);
52          long start = System.nanoTime();
53          for (Thread thread : threads) {
54              thread.join();
55          }
56          assertThat("Shouldn't wait that long for all threads to join!",
57              TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start), is(0L));
58          // Only meaning full if you don't put values in the chm!
59          System.out.println(totalRuns.get() / DURATION / THREADS + " tps per thread" );
60          assertThat(errors.get(), is(0L));
61      }
62  }