List of usage examples for com.google.common.util.concurrent Service state
State state();
From source file:io.pravega.common.concurrent.ServiceShutdownListener.java
/** * Awaits for the given Services to shut down, whether normally or exceptionally. * * @param services The services to monitor. * @param throwIfFailed Throw an IllegalStateException if any of the services ended up in a FAILED state. * @param <T> The type of the Collection's elements. *//* www.j ava 2s . c o m*/ public static <T extends Service> void awaitShutdown(Collection<T> services, boolean throwIfFailed) { int failureCount = 0; for (Service service : services) { try { service.awaitTerminated(); } catch (IllegalStateException ex) { if (throwIfFailed || service.state() != Service.State.FAILED) { failureCount++; } } } if (failureCount > 0) { throw new IllegalStateException(String.format("%d store(s) could not be shut down.", failureCount)); } }
From source file:io.pravega.common.concurrent.ServiceHelpers.java
/** * Asynchronously starts a Service and returns a CompletableFuture that will indicate when it is running. * * @param service The Service to start. * @param executor An Executor to use for callback invocations. * @return A CompletableFuture that will be completed when the service enters a RUNNING state, or completed * exceptionally if the service failed to start. *//*from ww w . j a v a2 s. co m*/ public static CompletableFuture<Void> startAsync(Service service, Executor executor) { // Service.startAsync() will fail if the service is not in a NEW state. That is, if it is already RUNNING or // STARTED, then the method will fail synchronously, hence we are not in danger of not invoking our callbacks, // as long as we register the Listener before we attempt to start. // Nevertheless, do make a sanity check since once added, a Listener cannot be removed. Preconditions.checkState(service.state() == Service.State.NEW, "Service expected to be %s but was %s.", Service.State.NEW, service.state()); Preconditions.checkNotNull(executor, "executor"); CompletableFuture<Void> result = new CompletableFuture<>(); service.addListener(new StartupListener(result), executor); service.startAsync(); return result; }
From source file:org.apache.twill.internal.Services.java
/** * Returns a {@link ListenableFuture} that will be completed when the given service is stopped. If the service * stopped due to error, the failure cause would be reflected in the future. * * @param service The {@link Service} to block on. * @return A {@link ListenableFuture} that will be completed when the service is stopped. *///from w w w . jav a 2 s . c o m public static ListenableFuture<Service.State> getCompletionFuture(Service service) { final SettableFuture<Service.State> resultFuture = SettableFuture.create(); service.addListener(new ServiceListenerAdapter() { @Override public void terminated(Service.State from) { resultFuture.set(Service.State.TERMINATED); } @Override public void failed(Service.State from, Throwable failure) { resultFuture.setException(failure); } }, Threads.SAME_THREAD_EXECUTOR); Service.State state = service.state(); if (state == Service.State.TERMINATED) { return Futures.immediateFuture(state); } else if (state == Service.State.FAILED) { return Futures .immediateFailedFuture(new IllegalStateException("Service failed with unknown exception.")); } return resultFuture; }
From source file:io.pravega.common.concurrent.ServiceShutdownListener.java
/** * Awaits for the given Services to shut down, whether normally or exceptionally. * * @param services The services to monitor. * @param timeout Timeout for the operation. * @param throwIfFailed Throw an IllegalStateException if any of the services ended up in a FAILED state. * @param <T> The type of the Collection's elements. * @throws TimeoutException If the store did not shut down within the specified amount of time. This exception is * thrown regardless of the value passed in as throwIfFailed. *///from w w w . j av a2s .com public static <T extends Service> void awaitShutdown(Collection<T> services, Duration timeout, boolean throwIfFailed) throws TimeoutException { TimeoutTimer timer = new TimeoutTimer(timeout); int failureCount = 0; for (Service service : services) { try { // We wait on each store individually, making sure we decrease the available timeout. It does not matter // if we do it sequentially or in parallel - our contract is to wait for all services within a timeout; // if any of the services did not respond within the given time, it is a reason for failure. service.awaitTerminated(timer.getRemaining().toMillis(), TimeUnit.MILLISECONDS); } catch (IllegalStateException ex) { if (throwIfFailed || service.state() != Service.State.FAILED) { failureCount++; } } } if (failureCount > 0) { throw new IllegalStateException(String.format("%d store(s) could not be shut down.", failureCount)); } }
From source file:io.pravega.common.concurrent.ServiceHelpers.java
/** * Attaches the given callbacks which will be invoked when the given Service enters a TERMINATED or FAILED state. * The callbacks are optional and may be invoked synchronously if the Service is already in one of these states. * * @param service The Service to attach to. * @param terminatedCallback (Optional) A Runnable that will be invoked if the Service enters a TERMINATED state. * @param failureCallback (Optional) A Runnable that will be invoked if the Service enters a FAILED state. * @param executor An Executor to use for callback invocations. *//*w ww .j a v a 2 s. c o m*/ public static void onStop(Service service, Runnable terminatedCallback, Consumer<Throwable> failureCallback, Executor executor) { ShutdownListener listener = new ShutdownListener(terminatedCallback, failureCallback); service.addListener(listener, executor); // addListener() will not invoke the callbacks if the service is already in a terminal state. As such, we need to // manually check for these states after registering the listener and invoke the appropriate callback. The // ShutdownListener will make sure they are not invoked multiple times. Service.State state = service.state(); if (state == Service.State.FAILED) { // We don't care (or know) the state from which we came, so we just pass some random one. listener.failed(Service.State.FAILED, service.failureCause()); } else if (state == Service.State.TERMINATED) { listener.terminated(Service.State.TERMINATED); } }
From source file:org.apache.onami.lifecycle.guava.GuavaServiceStartModule.java
@Override protected void configure() { bindLifeCycle(Service.class, "startAsync", new InvocationResultHandler() { public void afterInvocation(Object obj) throws Throwable { Service svc = (Service) obj; if (svc.state() == Service.State.FAILED) { throw svc.failureCause(); }/* w w w . j av a 2 s . com*/ } }); }
From source file:com.continuuity.weave.internal.WeaveContainerMain.java
private static Service wrapService(final ZKClientService zkClientService, final Service containerService) { return new Service() { @Override//from w w w . j a v a 2s . c om public ListenableFuture<State> start() { return Futures.transform(Services.chainStart(zkClientService, containerService), new AsyncFunction<List<ListenableFuture<State>>, State>() { @Override public ListenableFuture<State> apply(List<ListenableFuture<State>> input) throws Exception { return input.get(1); } }); } @Override public State startAndWait() { return Futures.getUnchecked(start()); } @Override public boolean isRunning() { return containerService.isRunning(); } @Override public State state() { return containerService.state(); } @Override public ListenableFuture<State> stop() { return Futures.transform(Services.chainStop(containerService, zkClientService), new AsyncFunction<List<ListenableFuture<State>>, State>() { @Override public ListenableFuture<State> apply(List<ListenableFuture<State>> input) throws Exception { return input.get(0); } }); } @Override public State stopAndWait() { return Futures.getUnchecked(stop()); } @Override public void addListener(Listener listener, Executor executor) { containerService.addListener(listener, executor); } }; }
From source file:org.icgc.dcc.submission.core.DccRuntime.java
private void tryStopService(Service service) { try {//from w ww. j a v a 2 s . c o m log.info("Service {} is [{}]. Stopping.", service.getClass(), service.state()); service.stopAsync().awaitTerminated(); val expectedState = TERMINATED; val actualState = service.state(); checkState(expectedState == actualState, "Service should be '%s', instead was found '%s'", expectedState, actualState); log.info("Service {} is now [{}]", service.getClass(), actualState); } catch (UncheckedExecutionException e) { log.error("Failed to stop service {}: {}", service.getClass(), e.getCause().getMessage()); throw e; } }
From source file:org.icgc.dcc.submission.core.DccRuntime.java
private void tryStartService(Service service) { try {/*from w w w . j a va 2 s . c o m*/ log.info("Service {} is [{}]. Starting.", service.getClass(), service.state()); service.startAsync().awaitRunning(); val expectedState = RUNNING; val actualState = service.state(); checkState(expectedState == actualState, "Service should be '%s', instead was found '%s'", expectedState, actualState); log.info("Service {} is now [{}]", service.getClass(), actualState); } catch (UncheckedExecutionException e) { log.warn("Failed to start service {}: {}", service.getClass(), e.getCause().getMessage()); throw e; } }
From source file:org.apache.twill.internal.CompositeService.java
private void stopAll() throws Exception { Throwable failureCause = null; // Stop services in reverse order. Iterator<Service> itor = services.descendingIterator(); while (itor.hasNext()) { Service service = itor.next(); try {// ww w.j a v a 2s.c om if (service.isRunning() || service.state() == State.STARTING) { service.stopAndWait(); } } catch (UncheckedExecutionException e) { // Just catch as we want all services stopped if (failureCause == null) { failureCause = e.getCause(); } else { // Log for sub-sequence service shutdown error, as only the first failure cause will be thrown. LOG.warn("Failed to stop service {}", service, e); } } } if (failureCause != null) { Throwables.propagateIfPossible(failureCause, Exception.class); throw new RuntimeException(failureCause); } }