1package com.google.inject.service; 2 3 4import junit.framework.TestCase; 5 6import java.util.concurrent.CountDownLatch; 7import java.util.concurrent.ExecutionException; 8import java.util.concurrent.ExecutorService; 9import java.util.concurrent.Executors; 10import java.util.concurrent.Future; 11import java.util.concurrent.TimeUnit; 12import java.util.concurrent.TimeoutException; 13import java.util.concurrent.atomic.AtomicInteger; 14 15/** 16 * Tests using Async Service. 17 */ 18 19public class SingleServiceIntegrationTest extends TestCase { 20 21 public final void testAsyncServiceLifecycle() throws Exception { 22 ExecutorService executor = Executors.newSingleThreadExecutor(); 23 24 final CountDownLatch startLatch = new CountDownLatch(1); 25 final CountDownLatch stopLatch = new CountDownLatch(1); 26 AsyncService service = new AsyncService(executor) { 27 @Override protected void onStart() { 28 assertEquals(1, startLatch.getCount()); 29 assertEquals(1, stopLatch.getCount()); 30 31 startLatch.countDown(); 32 } 33 34 @Override protected void onStop() { 35 assertEquals(0, startLatch.getCount()); 36 assertEquals(1, stopLatch.getCount()); 37 38 stopLatch.countDown(); 39 } 40 }; 41 42 Future<?> future = service.start(); 43 // This should not pass! TODO(sameb): Why? Looks like it should to me 44 assertTrue(startLatch.await(2, TimeUnit.SECONDS)); 45 // onStart() is called before the state is set to STARTED, so we need 46 // to wait until the Future finishes to guarantee it really was started. 47 // This still manages to test what we want because the startLatch check 48 // is before this. 49 future.get(1, TimeUnit.SECONDS); 50 51 service.stop(); 52 assertTrue(stopLatch.await(2, TimeUnit.SECONDS)); 53 54 executor.shutdown(); 55 assertEquals(0, startLatch.getCount()); 56 assertEquals(0, stopLatch.getCount()); 57 } 58 59 public final void testAsyncServiceBlockingLifecycle() 60 throws InterruptedException, ExecutionException, TimeoutException { 61 ExecutorService executor = Executors.newSingleThreadExecutor(); 62 63 final AtomicInteger integer = new AtomicInteger(2); 64 AsyncService service = new AsyncService(executor) { 65 @Override protected void onStart() { 66 assertEquals(2, integer.getAndDecrement()); 67 } 68 69 @Override protected void onStop() { 70 assertEquals(1, integer.getAndDecrement()); 71 } 72 }; 73 74 service.start().get(2, TimeUnit.SECONDS); 75 service.stop().get(2, TimeUnit.SECONDS); 76 77 executor.shutdown(); 78 assertEquals(0, integer.get()); 79 } 80} 81