1 /* 2 * Copyright (C) 2008 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.testing; 18 19 import com.google.common.annotations.GwtCompatible; 20 import com.google.common.annotations.GwtIncompatible; 21 22 import junit.framework.TestCase; 23 24 import java.util.concurrent.Callable; 25 import java.util.concurrent.CountDownLatch; 26 import java.util.concurrent.ExecutorService; 27 import java.util.concurrent.Executors; 28 import java.util.concurrent.TimeUnit; 29 30 /** 31 * Unit test for {@link FakeTicker}. 32 * 33 * @author benyu@google.com (Jige Yu) 34 */ 35 @GwtCompatible(emulated = true) 36 public class FakeTickerTest extends TestCase { 37 testAdvance()38 public void testAdvance() { 39 FakeTicker ticker = new FakeTicker(); 40 assertEquals(0, ticker.read()); 41 assertSame(ticker, ticker.advance(10)); 42 assertEquals(10, ticker.read()); 43 ticker.advance(1, TimeUnit.MILLISECONDS); 44 assertEquals(1000010L, ticker.read()); 45 } 46 47 @GwtIncompatible("concurrency") 48 testConcurrentAdvance()49 public void testConcurrentAdvance() throws Exception { 50 final FakeTicker ticker = new FakeTicker(); 51 52 int numberOfThreads = 64; 53 ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); 54 final CountDownLatch startLatch = new CountDownLatch(numberOfThreads); 55 final CountDownLatch doneLatch = new CountDownLatch(numberOfThreads); 56 for (int i = numberOfThreads; i > 0; i--) { 57 executorService.submit(new Callable<Void>() { 58 @Override 59 public Void call() throws Exception { 60 // adds two nanoseconds to the ticker 61 startLatch.countDown(); 62 startLatch.await(); 63 ticker.advance(1L); 64 Thread.sleep(10); 65 ticker.advance(1L); 66 doneLatch.countDown(); 67 return null; 68 } 69 }); 70 } 71 doneLatch.await(); 72 assertEquals(numberOfThreads * 2, ticker.read()); 73 } 74 } 75