Here are the examples of the java api class com.google.common.util.concurrent.Service taken from open source projects.
1. ServicesTest#testCompletion()
View license@Test public void testCompletion() throws ExecutionException, InterruptedException { Service service = new DummyService("s1", new AtomicBoolean()); ListenableFuture<Service.State> completion = Services.getCompletionFuture(service); service.start(); service.stop(); completion.get(); AtomicBoolean transiting = new AtomicBoolean(); service = new DummyService("s2", transiting); completion = Services.getCompletionFuture(service); service.startAndWait(); transiting.set(true); service.stop(); try { completion.get(); Assert.assertTrue(false); } catch (ExecutionException e) { } }
2. ServicesTest#testCompletion()
View license@Test public void testCompletion() throws ExecutionException, InterruptedException { Service service = new DummyService("s1", new AtomicBoolean()); ListenableFuture<Service.State> completion = Services.getCompletionFuture(service); service.start(); service.stop(); completion.get(); AtomicBoolean transiting = new AtomicBoolean(); service = new DummyService("s2", transiting); completion = Services.getCompletionFuture(service); service.startAndWait(); transiting.set(true); service.stop(); try { completion.get(); Assert.assertTrue(false); } catch (ExecutionException e) { } }
3. RetryOnStartFailureServiceTest#testRetryFail()
View license@Test public void testRetryFail() throws InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); Service service = new RetryOnStartFailureService(createServiceSupplier(1000, startLatch, new CountDownLatch(1)), RetryStrategies.limit(10, RetryStrategies.fixDelay(10, TimeUnit.MILLISECONDS))); final CountDownLatch failureLatch = new CountDownLatch(1); service.addListener(new ServiceListenerAdapter() { @Override public void failed(Service.State from, Throwable failure) { failureLatch.countDown(); } }, Threads.SAME_THREAD_EXECUTOR); service.start(); Assert.assertTrue(failureLatch.await(1, TimeUnit.SECONDS)); Assert.assertFalse(startLatch.await(100, TimeUnit.MILLISECONDS)); }
4. AbstractProgramRuntimeServiceTest#testUpdateDeadLock()
View license@Test(timeout = 5000L) public void testUpdateDeadLock() { // This test is for testing (CDAP-3716) // Create a service to simulate an existing running app. Service service = new TestService(); Id.Program programId = Id.Program.from(Id.Namespace.DEFAULT, "dummyApp", ProgramType.WORKER, "dummy"); RunId runId = RunIds.generate(); ProgramRuntimeService.RuntimeInfo extraInfo = createRuntimeInfo(service, programId, runId); service.startAndWait(); ProgramRunnerFactory runnerFactory = createProgramRunnerFactory(); TestProgramRuntimeService runtimeService = new TestProgramRuntimeService(CConfiguration.create(), runnerFactory, null, extraInfo); runtimeService.startAndWait(); // The lookup will get deadlock for CDAP-3716 Assert.assertNotNull(runtimeService.lookup(programId, runId)); service.stopAndWait(); runtimeService.stopAndWait(); }
5. ApplicationMasterMain#main()
View license/** * Starts the application master. */ public static void main(String[] args) throws Exception { String zkConnect = System.getenv(EnvKeys.WEAVE_ZK_CONNECT); File weaveSpec = new File(Constants.Files.WEAVE_SPEC); RunId runId = RunIds.fromString(System.getenv(EnvKeys.WEAVE_RUN_ID)); ZKClientService zkClientService = ZKClientServices.delegate(ZKClients.reWatchOnExpire(ZKClients.retryOnFailure(ZKClientService.Builder.of(zkConnect).build(), RetryStrategies.fixDelay(1, TimeUnit.SECONDS)))); Configuration conf = new YarnConfiguration(new HdfsConfiguration(new Configuration())); Service service = new ApplicationMasterService(runId, zkClientService, weaveSpec, new VersionDetectYarnAMClientFactory(conf), createAppLocation(conf)); new ApplicationMasterMain(String.format("%s/%s/kafka", zkConnect, runId.getId())).doMain(zkClientService, service); }
6. RetryOnStartFailureService#doStop()
View license@Override protected void doStop() { startupThread.interrupt(); Uninterruptibles.joinUninterruptibly(startupThread); Service service = currentDelegate; if (service != null) { Futures.addCallback(service.stop(), new FutureCallback<State>() { @Override public void onSuccess(State result) { notifyStopped(); } @Override public void onFailure(Throwable t) { notifyFailed(t); } }, Threads.SAME_THREAD_EXECUTOR); } else { notifyStopped(); } }
7. PubsubTestUtil#startPubsub()
View license/** * Starts the pubsub system and gets a handle to the event sink where pubsub events may be sent. * * @param injector Injector where the pubsub system was installed. * @return The pubsub event sink. * @throws Exception If the pubsub system failed to start. */ public static EventSink startPubsub(Injector injector) throws Exception { // TODO(wfarner): Make it easier to write a unit test wired for pubsub events. // In this case, a trade-off was made to avoid installing several distant modules and providing // required bindings that seem unrelated from this code. Set<Service> services = injector.getInstance(Key.get(new TypeLiteral<Set<Service>>() { }, AppStartup.class)); for (Service service : services) { service.startAsync().awaitRunning(); } return injector.getInstance(EventSink.class); }
8. CronIT#testJobsAreScheduled()
View license@Test public void testJobsAreScheduled() throws Exception { auroraCronJob.execute(isA(JobExecutionContext.class)); control.replay(); final Scheduler scheduler = injector.getInstance(Scheduler.class); storage.write((NoResult.Quiet) storeProvider -> storeProvider.getCronJobStore().saveAcceptedJob(CRON_JOB)); final CountDownLatch cronRan = new CountDownLatch(1); scheduler.getListenerManager().addTriggerListener(new CountDownWhenComplete(cronRan)); Service service = boot(); cronRan.await(); service.stopAsync().awaitTerminated(); }
9. CronIT#testCronSchedulerLifecycle()
View license@Test public void testCronSchedulerLifecycle() throws Exception { control.replay(); Scheduler scheduler = injector.getInstance(Scheduler.class); assertFalse(scheduler.isStarted()); Service cronLifecycle = boot(); assertTrue(cronLifecycle.isRunning()); assertTrue(scheduler.isStarted()); cronLifecycle.stopAsync().awaitTerminated(); assertFalse(cronLifecycle.isRunning()); assertTrue(scheduler.isShutdown()); }
10. AsyncModuleTest#testBindings()
View license@Test public void testBindings() throws Exception { Injector injector = createInjector(new AsyncModule()); control.replay(); Set<Service> services = injector.getInstance(Key.get(new TypeLiteral<Set<Service>>() { }, AppStartup.class)); for (Service service : services) { service.startAsync().awaitRunning(); } injector.getBindings(); assertEquals(ImmutableMap.of(RegisterGauges.TIMEOUT_QUEUE_GAUGE, 0, RegisterGauges.ASYNC_TASKS_GAUGE, 0L, RegisterGauges.DELAY_QUEUE_GAUGE, 0), statsProvider.getAllValues()); }
11. ServicesTest#testChain()
View license@Test public void testChain() throws ExecutionException, InterruptedException { AtomicBoolean transiting = new AtomicBoolean(false); Service s1 = new DummyService("s1", transiting); Service s2 = new DummyService("s2", transiting); Service s3 = new DummyService("s3", transiting); Futures.allAsList(Services.chainStart(s1, s2, s3).get()).get(); Futures.allAsList(Services.chainStop(s3, s2, s1).get()).get(); }
12. ServicesTest#testChain()
View license@Test public void testChain() throws ExecutionException, InterruptedException { AtomicBoolean transiting = new AtomicBoolean(false); Service s1 = new DummyService("s1", transiting); Service s2 = new DummyService("s2", transiting); Service s3 = new DummyService("s3", transiting); Futures.allAsList(Services.chainStart(s1, s2, s3).get()).get(); Futures.allAsList(Services.chainStop(s3, s2, s1).get()).get(); }
13. RetryOnStartFailureServiceTest#testFailureStop()
View license@Test(timeout = 5000) public void testFailureStop() throws InterruptedException { // This test the service can be stopped during failure retry CountDownLatch failureLatch = new CountDownLatch(1); Service service = new RetryOnStartFailureService(createServiceSupplier(1000, new CountDownLatch(1), failureLatch), RetryStrategies.fixDelay(10, TimeUnit.MILLISECONDS)); service.startAndWait(); Assert.assertTrue(failureLatch.await(1, TimeUnit.SECONDS)); service.stopAndWait(); }
14. ServicesTest#testGetServices()
View license@Test public void testGetServices() throws Exception { Service newService = createMock(Service.class); expect(newService.state()).andReturn(State.NEW); Service failedService = createMock(Service.class); expect(failedService.state()).andReturn(State.FAILED); Exception failureCause = new Exception(FAILURE_CAUSE_REASON); expect(failedService.failureCause()).andReturn(failureCause); Service runningService = createMock(Service.class); expect(runningService.state()).andReturn(State.RUNNING); expect(startupServiceManager.servicesByState()).andReturn(ImmutableMultimap.of(State.RUNNING, runningService, State.FAILED, failedService)); expect(activeServicesManager.servicesByState()).andReturn(ImmutableMultimap.of(State.NEW, newService)); control.replay(); assertEquals(ImmutableList.of(ImmutableMap.of("name", newService.getClass().getSimpleName(), "state", State.NEW), ImmutableMap.of("name", failedService.getClass().getSimpleName(), "state", State.RUNNING), ImmutableMap.of("name", failedService.getClass().getSimpleName(), "state", State.FAILED, "failureCause", failureCause.toString())), servicesServlet.getServices().getEntity()); }
15. CompositeServiceTest#testErrorStart()
View license@Test public void testErrorStart() throws InterruptedException { List<Service> services = Lists.newArrayList(); // Create 5 services. The forth one will got a start failure. Semaphore semaphore = new Semaphore(0); for (int i = 0; i < 5; i++) { services.add(new TestService(semaphore, i, i == 3)); } Service service = new CompositeService(services); try { service.start().get(); Assert.fail(); } catch (ExecutionException e) { } // Verify all services are not in running state Assert.assertTrue(Iterables.all(services, Predicates.not(serviceStatePredicate(Service.State.RUNNING)))); // There should be one service in error state Assert.assertTrue(Iterables.removeIf(services, serviceStatePredicate(Service.State.FAILED))); for (Service s : services) { Assert.assertNotEquals(3, ((TestService) s).getOrder()); } }
16. SystemTestBase#baseTeardown()
View license@After public void baseTeardown() throws Exception { for (final HeliosClient client : clients) { client.close(); } clients.clear(); for (final Service service : services) { try { service.stopAsync(); } catch (Exception e) { log.error("Uncaught exception", e); } } for (final Service service : services) { try { service.awaitTerminated(); } catch (Exception e) { log.error("Service failed", e); } } services.clear(); // Clean up docker try (final DockerClient dockerClient = getNewDockerClient()) { final List<Container> containers = dockerClient.listContainers(); for (final Container container : containers) { for (final String name : container.names()) { if (name.contains(testTag)) { try { dockerClient.killContainer(container.id()); } catch (DockerException e) { e.printStackTrace(); } break; } } } } catch (Exception e) { log.error("Docker client exception", e); } if (zk != null) { zk.close(); } listThreads(); }
17. RetryOnStartFailureServiceTest#testRetrySucceed()
View license@Test public void testRetrySucceed() throws InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); Service service = new RetryOnStartFailureService(createServiceSupplier(3, startLatch, new CountDownLatch(1)), RetryStrategies.fixDelay(10, TimeUnit.MILLISECONDS)); service.startAndWait(); Assert.assertTrue(startLatch.await(1, TimeUnit.SECONDS)); }
18. WeaveContainerMain#main()
View license/** * Main method for launching a {@link WeaveContainerService} which runs * a {@link com.continuuity.weave.api.WeaveRunnable}. */ public static void main(final String[] args) throws Exception { // Try to load the secure store from localized file, which AM requested RM to localize it for this container. loadSecureStore(); String zkConnectStr = System.getenv(EnvKeys.WEAVE_ZK_CONNECT); File weaveSpecFile = new File(Constants.Files.WEAVE_SPEC); RunId appRunId = RunIds.fromString(System.getenv(EnvKeys.WEAVE_APP_RUN_ID)); RunId runId = RunIds.fromString(System.getenv(EnvKeys.WEAVE_RUN_ID)); String runnableName = System.getenv(EnvKeys.WEAVE_RUNNABLE_NAME); int instanceId = Integer.parseInt(System.getenv(EnvKeys.WEAVE_INSTANCE_ID)); int instanceCount = Integer.parseInt(System.getenv(EnvKeys.WEAVE_INSTANCE_COUNT)); ZKClientService zkClientService = ZKClientServices.delegate(ZKClients.reWatchOnExpire(ZKClients.retryOnFailure(ZKClientService.Builder.of(zkConnectStr).build(), RetryStrategies.fixDelay(1, TimeUnit.SECONDS)))); DiscoveryService discoveryService = new ZKDiscoveryService(zkClientService); WeaveSpecification weaveSpec = loadWeaveSpec(weaveSpecFile); renameLocalFiles(weaveSpec.getRunnables().get(runnableName)); WeaveRunnableSpecification runnableSpec = weaveSpec.getRunnables().get(runnableName).getRunnableSpecification(); ContainerInfo containerInfo = new EnvContainerInfo(); Arguments arguments = decodeArgs(); BasicWeaveContext context = new BasicWeaveContext(runId, appRunId, containerInfo.getHost(), arguments.getRunnableArguments().get(runnableName).toArray(new String[0]), arguments.getArguments().toArray(new String[0]), runnableSpec, instanceId, discoveryService, instanceCount, containerInfo.getMemoryMB(), containerInfo.getVirtualCores()); Configuration conf = new YarnConfiguration(new HdfsConfiguration(new Configuration())); Service service = new WeaveContainerService(context, containerInfo, getContainerZKClient(zkClientService, appRunId, runnableName), runId, runnableSpec, getClassLoader(), createAppLocation(conf)); new WeaveContainerMain().doMain(zkClientService, service); }
19. ServiceMain#doMain()
View licenseprotected final void doMain(final Service mainService, Service... prerequisites) throws ExecutionException, InterruptedException { configureLogger(); Service requiredServices = new CompositeService(prerequisites); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mainService.stopAndWait(); } }); // Listener for state changes of the service ListenableFuture<Service.State> completion = Services.getCompletionFuture(mainService); Throwable initFailure = null; try { try { // Starts the service LOG.info("Starting service {}.", mainService); Futures.allAsList(Services.chainStart(requiredServices, mainService).get()).get(); LOG.info("Service {} started.", mainService); } catch (Throwable t) { LOG.error("Exception when starting service {}.", mainService, t); initFailure = t; } try { if (initFailure == null) { completion.get(); LOG.info("Service {} completed.", mainService); } } catch (Throwable t) { LOG.error("Exception thrown from service {}.", mainService, t); throw Throwables.propagate(t); } } finally { requiredServices.stopAndWait(); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { ((LoggerContext) loggerFactory).stop(); } if (initFailure != null) { // Exit with the init fail exit code. System.exit(ContainerExitCodes.INIT_FAILED); } } }
20. TwillContainerMain#main()
View license/** * Main method for launching a {@link TwillContainerService} which runs * a {@link org.apache.twill.api.TwillRunnable}. */ public static void main(final String[] args) throws Exception { // Try to load the secure store from localized file, which AM requested RM to localize it for this container. loadSecureStore(); String zkConnectStr = System.getenv(EnvKeys.TWILL_ZK_CONNECT); File twillSpecFile = new File(Constants.Files.TWILL_SPEC); RunId appRunId = RunIds.fromString(System.getenv(EnvKeys.TWILL_APP_RUN_ID)); RunId runId = RunIds.fromString(System.getenv(EnvKeys.TWILL_RUN_ID)); String runnableName = System.getenv(EnvKeys.TWILL_RUNNABLE_NAME); int instanceId = Integer.parseInt(System.getenv(EnvKeys.TWILL_INSTANCE_ID)); int instanceCount = Integer.parseInt(System.getenv(EnvKeys.TWILL_INSTANCE_COUNT)); ZKClientService zkClientService = createZKClient(zkConnectStr, System.getenv(EnvKeys.TWILL_APP_NAME)); ZKDiscoveryService discoveryService = new ZKDiscoveryService(zkClientService); ZKClient appRunZkClient = getAppRunZKClient(zkClientService, appRunId); TwillSpecification twillSpec = loadTwillSpec(twillSpecFile); TwillRunnableSpecification runnableSpec = twillSpec.getRunnables().get(runnableName).getRunnableSpecification(); ContainerInfo containerInfo = new EnvContainerInfo(); Arguments arguments = decodeArgs(); BasicTwillContext context = new BasicTwillContext(runId, appRunId, containerInfo.getHost(), arguments.getRunnableArguments().get(runnableName).toArray(new String[0]), arguments.getArguments().toArray(new String[0]), runnableSpec, instanceId, discoveryService, discoveryService, appRunZkClient, instanceCount, containerInfo.getMemoryMB(), containerInfo.getVirtualCores()); ZKClient containerZKClient = getContainerZKClient(zkClientService, appRunId, runnableName); Configuration conf = new YarnConfiguration(new HdfsConfiguration(new Configuration())); Service service = new TwillContainerService(context, containerInfo, containerZKClient, runId, runnableSpec, getClassLoader(), createAppLocation(conf)); new TwillContainerMain().doMain(service, new LogFlushService(), zkClientService, new TwillZKPathService(containerZKClient, runId)); }
21. CompositeServiceTest#testOrder()
View license@Test public void testOrder() throws InterruptedException, ExecutionException, TimeoutException { List<Service> services = Lists.newArrayList(); // Start 10 services and check their start sequence is ordered. Semaphore semaphore = new Semaphore(0); for (int i = 0; i < 10; i++) { services.add(new TestService(semaphore, i)); } Service service = new CompositeService(services); service.start().get(5, TimeUnit.SECONDS); // There should be 10 permits after all 10 services started Assert.assertTrue(semaphore.tryAcquire(10, 5, TimeUnit.SECONDS)); // Check all services are running Assert.assertTrue(Iterables.all(services, serviceStatePredicate(Service.State.RUNNING))); // Release 10 permits for the stop sequence to start semaphore.release(10); service.stop().get(5, TimeUnit.SECONDS); // There should be no permit left after all 10 services stopped Assert.assertFalse(semaphore.tryAcquire(10)); // Check all services are stopped Assert.assertTrue(Iterables.all(services, serviceStatePredicate(Service.State.TERMINATED))); }
22. CompositeService#startUp()
View license@Override protected void startUp() throws Exception { Throwable failureCause = null; for (Service service : services) { try { service.startAndWait(); } catch (UncheckedExecutionException e) { failureCause = e.getCause(); break; } } if (failureCause != null) { // Stop all running services and then throw the failure exception try { stopAll(); } catch (Throwable t) { LOG.warn("Failed when stopping all services on start failure", t); } Throwables.propagateIfPossible(failureCause, Exception.class); throw new RuntimeException(failureCause); } }
23. AutoRestartingServiceTest#testServiceStaysRunningIfThrowOnRunning()
View license@Test public void testServiceStaysRunningIfThrowOnRunning() throws InterruptedException { final RecordingSupplier recordingSupplier = new RecordingSupplier<>(WaitThenThrowOnRunService::new); final AutoRestartingService<WaitThenThrowOnRunService> restartingService = new AutoRestartingService<>(recordingSupplier, () -> true); final Service initialDelegate = restartingService.getDelegate(); try { // This waits for this instance of the service to be terminated restartingService.startAsync(); restartingService.getDelegate().runLatch.countDown(); restartingService.stopAndAwait(); // This may or may not throw an exception depending on the state of the service } catch (IllegalStateException expected) { if (expected.getCause() == null) { throw expected; } assertThat(expected.getCause()).hasMessage("kaboom!"); } try { restartingService.startAsync(); restartingService.getDelegate().runLatch.countDown(); restartingService.stopAndAwait(); // This may or may not throw an exception depending on the state of the service } catch (IllegalStateException expected) { if (expected.getCause() == null) { throw expected; } assertThat(expected.getCause()).hasMessage("kaboom!"); } assertNotEquals("A new service should be created when the old service terminated", initialDelegate, restartingService.getDelegate()); }
24. AbstractMasterTwillRunnable#run()
View license@Override public void run() { runThread = Thread.currentThread(); LOG.info("Starting runnable {}", name); SettableFuture<String> completionFuture = SettableFuture.create(); for (Service service : services) { service.addListener(createServiceListener(service.getClass().getName(), completionFuture), Threads.SAME_THREAD_EXECUTOR); } Futures.getUnchecked(Services.chainStart(services.get(0), services.subList(1, services.size()).toArray(new Service[0]))); LOG.info("Runnable started {}", name); try { // exit as soon as any service completes completionFuture.get(); } catch (InterruptedException e) { LOG.debug("Waiting on latch interrupted {}", name); Thread.currentThread().interrupt(); } catch (ExecutionException e) { throw Throwables.propagate(e.getCause()); } List<Service> reverse = Lists.reverse(services); Futures.getUnchecked(Services.chainStop(reverse.get(0), reverse.subList(1, reverse.size()).toArray(new Service[0]))); LOG.info("Runnable stopped {}", name); }
25. ServiceMain#doMain()
View licenseprotected final void doMain(final Service mainService, Service... prerequisites) throws ExecutionException, InterruptedException { if (Boolean.parseBoolean(System.getProperty("twill.disable.kafka"))) { LOG.info("Log collection through kafka disabled"); } else { configureLogger(); } Service requiredServices = new CompositeService(prerequisites); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mainService.stopAndWait(); } }); // Listener for state changes of the service ListenableFuture<Service.State> completion = Services.getCompletionFuture(mainService); Throwable initFailure = null; try { try { // Starts the service LOG.info("Starting service {}.", mainService); Futures.allAsList(Services.chainStart(requiredServices, mainService).get()).get(); LOG.info("Service {} started.", mainService); } catch (Throwable t) { LOG.error("Exception when starting service {}.", mainService, t); initFailure = t; } try { if (initFailure == null) { completion.get(); LOG.info("Service {} completed.", mainService); } } catch (Throwable t) { LOG.error("Exception thrown from service {}.", mainService, t); throw Throwables.propagate(t); } } finally { requiredServices.stopAndWait(); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { ((LoggerContext) loggerFactory).stop(); } if (initFailure != null) { // Exit with the init fail exit code. System.exit(ContainerExitCodes.INIT_FAILED); } } }
26. CronIT#boot()
View licenseprivate Service boot() { Service service = injector.getInstance(CronLifecycle.class); service.startAsync().awaitRunning(); return service; }