Top Description Inners Fields Constructors Methods
com.google.common.util.concurrent

public final Class ServiceManager

extends Object
implements ServiceManagerBridge
Class Inheritance
All Implemented Interfaces
com.google.common.util.concurrent.ServiceManagerBridge
Annotations
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull, .Preconditions.checkState, .Predicates.equalTo, .Predicates.in, .Predicates.instanceOf, .Predicates.not, com.google.common.util.concurrent.Internal.toNanosSaturated, .MoreExecutors.directExecutor, .Service.State.FAILED, .Service.State.NEW, .Service.State.RUNNING, .Service.State.STARTING, .Service.State.STOPPING, .Service.State.TERMINATED, java.util.concurrent.TimeUnit.MILLISECONDS

A manager for monitoring and controlling a set of services. This class provides methods for starting, stopping and inspecting a collection of services. Additionally, users can monitor state transitions with the listener mechanism.

While it is recommended that service lifecycles be managed via this class, state transitions initiated via other mechanisms do not impact the correctness of its methods. For example, if the services are started by some mechanism besides startAsync, the listeners will be invoked when appropriate and awaitHealthy will still work as expected.

Here is a simple example of how to use a ServiceManager to start a server.

class Server {
  public static void main(String[] args) {
    Set<Service> services = ...;
    ServiceManager manager = new ServiceManager(services);
    manager.addListener(new Listener() {
        public void stopped() {}
        public void healthy() {
          // Services have been initialized and are healthy, start accepting requests...
        }
        public void failure(Service service) {
          // Something failed, at this point we could log it, notify a load balancer, or take
          // some other action.  For now we will just exit.
          System.exit(1);
        }
      },
      MoreExecutors.directExecutor());

    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        // Give the services 5 seconds to stop to ensure that we are responsive to shutdown
        // requests.
        try {
          manager.stopAsync().awaitStopped(5, TimeUnit.SECONDS);
        } catch (TimeoutException timeout) {
          // stopping timed out
        }
      }
    });
    manager.startAsync();  // start all the services asynchronously
  }
}

This class uses the ServiceManager's methods to start all of its services, to respond to service failure and to ensure that when the JVM is shutting down all the services are stopped.

Author
Luke Sandberg
Since
14.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
ServiceManager.EmptyServiceManagerWarning

This is never thrown but only used for logging.

private static class
public abstract static class
ServiceManager.Listener

A listener for the aggregate state changes of the services that are under management.

private static class
ServiceManager.NoOpService

A Service instance that does nothing.

private static class
ServiceManager.ServiceListener

A Service that wraps another service and times how long it takes for it to start and also calls the ServiceManagerState#transitionService(Service, State, State), to record the state transitions.

private static class
ServiceManager.ServiceManagerState

An encapsulation of all the mutable state of the ServiceManager that needs to be accessed by instances of ServiceListener.

Field Summary

Modifier and TypeField and Description
private static final ListenerCallQueue.Event<ServiceManager.Listener>
private static final LazyLogger
private final ImmutableList<Service>
private final ServiceManager.ServiceManagerState
state

An encapsulation of all of the state that is accessed by the service listeners.

private static final ListenerCallQueue.Event<ServiceManager.Listener>

Constructor Summary

AccessConstructor and Description
public
ServiceManager(Iterable<? extends Service>
The services to manage
services
)

Constructs a new instance for managing the given services.

Method Summary

Modifier and TypeMethod and Description
public void
addListener(ServiceManager.Listener
the listener to run when the manager changes state
listener
,
Executor
the executor in which the listeners callback methods will be run.
executor
)

Registers a Listener to be executed on the given executor.

public void
awaitHealthy()

Waits for the ServiceManager to become healthy.

public void
awaitHealthy(Duration
the maximum time to wait
timeout
)

Waits for the ServiceManager to become healthy for no more than the given time.

public void
awaitHealthy(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Waits for the ServiceManager to become healthy for no more than the given time.

public void
awaitStopped()

Waits for the all the services to reach a terminal state.

public void
awaitStopped(Duration
the maximum time to wait
timeout
)

Waits for the all the services to reach a terminal state for no more than the given time.

public void
awaitStopped(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Waits for the all the services to reach a terminal state for no more than the given time.

public boolean
isHealthy()

Returns true if all services are currently in the running state.

public ImmutableSetMultimap<Service.State, Service>
servicesByState()

Implements com.google.common.util.concurrent.ServiceManagerBridge.servicesByState.

Provides a snapshot of the current state of all the services under management.
public ServiceManager

Returns:

this
startAsync
()

Initiates service startup on all the services being managed.

public ImmutableMap<Service, Duration>

Returns:

Map of services and their corresponding startup time, the map entries will be ordered by startup time.
startupDurations
()

Returns the service load times.

public ImmutableMap<Service, Long>

Returns:

Map of services and their corresponding startup time in millis, the map entries will be ordered by startup time.
startupTimes
()

Returns the service load times.

public ServiceManager

Returns:

this
stopAsync
()

Initiates service shutdown if necessary on all the services being managed.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait