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

public abstract Class AbstractService

extends Object
implements Service
Class Inheritance
All Implemented Interfaces
com.google.common.util.concurrent.Service
Known Direct Subclasses
com.google.common.util.concurrent.ServiceManager.NoOpService, com.google.common.util.concurrent.AbstractIdleService.DelegateService, com.google.common.util.concurrent.AbstractScheduledService.ServiceDelegate
Annotations
@GwtIncompatible
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull, .Preconditions.checkState, com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException, .Service.State.FAILED, .Service.State.NEW, .Service.State.RUNNING, .Service.State.STARTING, .Service.State.STOPPING, .Service.State.TERMINATED, java.util.Objects.requireNonNull

Base class for implementing services that can handle doStart and doStop requests, responding to them with notifyStarted() and notifyStopped() callbacks. Its subclasses must manage threads manually; consider AbstractExecutionThreadService if you need only a single execution thread.
Authors
Jesse Wilson, Luke Sandberg
Since
1.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
private class
private class
private class
private static class
AbstractService.StateSnapshot

An immutable snapshot of the current state of the service.

Field Summary

Modifier and TypeField and Description
private final Monitor.Guard
private final Monitor.Guard
private final Monitor.Guard
private final Monitor.Guard
private final ListenerCallQueue<Service.Listener>
listeners

The listeners to notify during a state transition.

private final Monitor
private static final ListenerCallQueue.Event<Service.Listener>
private volatile AbstractService.StateSnapshot
snapshot

The current state of the service.

private static final ListenerCallQueue.Event<Service.Listener>
private static final ListenerCallQueue.Event<Service.Listener>
private static final ListenerCallQueue.Event<Service.Listener>
private static final ListenerCallQueue.Event<Service.Listener>
private static final ListenerCallQueue.Event<Service.Listener>
private static final ListenerCallQueue.Event<Service.Listener>
private static final ListenerCallQueue.Event<Service.Listener>

Constructor Summary

AccessConstructor and Description
protected
AbstractService()

Constructor for use by subclasses.

Method Summary

Modifier and TypeMethod and Description
public final void
addListener(Service.Listener
the listener to run when the service changes state is complete
listener
,
Executor
the executor in which the listeners callback methods will be run. For fast, lightweight listeners that would be safe to execute in any thread, consider MoreExecutors#directExecutor.
executor
)

Implements com.google.common.util.concurrent.Service.addListener.

Registers a Listener to be executed on the given executor.
public final void
public final void
awaitRunning(Duration
the maximum time to wait
timeout
)

Overrides default com.google.common.util.concurrent.Service.awaitRunning.

Waits for the Service to reach the running state for no more than the given time.
public final void
awaitRunning(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Implements com.google.common.util.concurrent.Service.awaitRunning.

Waits for the Service to reach the running state for no more than the given time.
public final void
public final void
awaitTerminated(Duration
the maximum time to wait
timeout
)

Overrides default com.google.common.util.concurrent.Service.awaitTerminated.

Waits for the Service to reach a terminal state (either terminated or failed) for no more than the given time.
public final void
awaitTerminated(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Implements com.google.common.util.concurrent.Service.awaitTerminated.

Waits for the Service to reach a terminal state (either terminated or failed) for no more than the given time.
private void
checkCurrentState(Service.State expected)

Checks that the current state is equal to the expected state.

private void
dispatchListenerEvents()

Attempts to execute all the listeners in listeners while not holding the monitor.

protected void
doCancelStart()

This method is called by stopAsync when the service is still starting (i.e. startAsync has been called but notifyStarted has not).

protected abstract void
doStart()

This method is called by startAsync to initiate service startup.

protected abstract void
doStop()

This method should be used to initiate service shutdown.

private void
enqueueFailedEvent(final Service.State from, final Throwable cause)

private void
private void
private void
private void
public final Throwable
failureCause()

Implements com.google.common.util.concurrent.Service.failureCause.

Returns the Throwable that caused this service to fail.
public final boolean
isRunning()

Implements com.google.common.util.concurrent.Service.isRunning.

Returns true if this service is running.
protected final void
notifyFailed(Throwable cause)

Invoke this method to transition the service to the State#FAILED.

protected final void
notifyStarted()

Implementing classes should invoke this method once their service has started.

protected final void
notifyStopped()

Implementing classes should invoke this method once their service has stopped.

public final Service
startAsync()

Implements com.google.common.util.concurrent.Service.startAsync.

If the service state is State#NEW, this initiates service startup and returns immediately.
public final Service.State
state()

Implements com.google.common.util.concurrent.Service.state.

Returns the lifecycle state of the service.
public final Service
stopAsync()

Implements com.google.common.util.concurrent.Service.stopAsync.

If the service is starting or running, this initiates service shutdown and returns immediately.
private static ListenerCallQueue.Event<Service.Listener>
private static ListenerCallQueue.Event<Service.Listener>
public String
toString()

Overrides java.lang.Object.toString.

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

Field Detail

hasReachedRunningback to summary
private final Monitor.Guard hasReachedRunning
isStartableback to summary
private final Monitor.Guard isStartable
isStoppableback to summary
private final Monitor.Guard isStoppable
isStoppedback to summary
private final Monitor.Guard isStopped
listenersback to summary
private final ListenerCallQueue<Service.Listener> listeners

The listeners to notify during a state transition.

monitorback to summary
private final Monitor monitor
RUNNING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> RUNNING_EVENT
snapshotback to summary
private volatile AbstractService.StateSnapshot snapshot

The current state of the service. This should be written with the lock held but can be read without it because it is an immutable object in a volatile field. This is desirable so that methods like state, failureCause and notably toString can be run without grabbing the lock.

To update this field correctly the lock must be held to guarantee that the state is consistent.

STARTING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> STARTING_EVENT
STOPPING_FROM_RUNNING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> STOPPING_FROM_RUNNING_EVENT
STOPPING_FROM_STARTING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> STOPPING_FROM_STARTING_EVENT
TERMINATED_FROM_NEW_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> TERMINATED_FROM_NEW_EVENT
TERMINATED_FROM_RUNNING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> TERMINATED_FROM_RUNNING_EVENT
TERMINATED_FROM_STARTING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> TERMINATED_FROM_STARTING_EVENT
TERMINATED_FROM_STOPPING_EVENTback to summary
private static final ListenerCallQueue.Event<Service.Listener> TERMINATED_FROM_STOPPING_EVENT

Constructor Detail

AbstractServiceback to summary
protected AbstractService()

Constructor for use by subclasses.

Method Detail

addListenerback to summary
public final void addListener(Service.Listener listener, Executor executor)

Implements com.google.common.util.concurrent.Service.addListener.

Doc from com.google.common.util.concurrent.Service.addListener.

Registers a Listener to be executed on the given executor. The listener will have the corresponding transition method called whenever the service changes state. The listener will not have previous state changes replayed, so it is suggested that listeners are added before the service starts.

addListener guarantees execution ordering across calls to a given listener but not across calls to multiple listeners. Specifically, a given listener will have its callbacks invoked in the same order as the underlying service enters those states. Additionally, at most one of the listener's callbacks will execute at once. However, multiple listeners' callbacks may execute concurrently, and listeners may execute in an order different from the one in which they were registered.

RuntimeExceptions thrown by a listener will be caught and logged. Any exception thrown during Executor.execute (e.g., a RejectedExecutionException) will be caught and logged.

Parameters
listener:Service.Listener

the listener to run when the service changes state is complete

executor:Executor

the executor in which the listeners callback methods will be run. For fast, lightweight listeners that would be safe to execute in any thread, consider MoreExecutors#directExecutor.

Annotations
@Override
Since
13.0
awaitRunningback to summary
public final void awaitRunning()

Implements com.google.common.util.concurrent.Service.awaitRunning.

Doc from com.google.common.util.concurrent.Service.awaitRunning.

Waits for the Service to reach the running state.

Annotations
@Override
awaitRunningback to summary
public final void awaitRunning(Duration timeout) throws TimeoutException

Overrides default com.google.common.util.concurrent.Service.awaitRunning.

Doc from com.google.common.util.concurrent.Service.awaitRunning.

Waits for the Service to reach the running state for no more than the given time.

Parameters
timeout:Duration

the maximum time to wait

Annotations
@Override
Exceptions
TimeoutException:
if the service has not reached the given state within the deadline
Since
28.0
awaitRunningback to summary
public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException

Implements com.google.common.util.concurrent.Service.awaitRunning.

Doc from com.google.common.util.concurrent.Service.awaitRunning.

Waits for the Service to reach the running state for no more than the given time.

Parameters
timeout:long

the maximum time to wait

unit:TimeUnit

the time unit of the timeout argument

Annotations
@Override
Exceptions
TimeoutException:
if the service has not reached the given state within the deadline
awaitTerminatedback to summary
public final void awaitTerminated()

Implements com.google.common.util.concurrent.Service.awaitTerminated.

Doc from com.google.common.util.concurrent.Service.awaitTerminated.

Waits for the Service to reach the terminated state.

Annotations
@Override
awaitTerminatedback to summary
public final void awaitTerminated(Duration timeout) throws TimeoutException

Overrides default com.google.common.util.concurrent.Service.awaitTerminated.

Doc from com.google.common.util.concurrent.Service.awaitTerminated.

Waits for the Service to reach a terminal state (either terminated or failed) for no more than the given time.

Parameters
timeout:Duration

the maximum time to wait

Annotations
@Override
Exceptions
TimeoutException:
if the service has not reached the given state within the deadline
Since
28.0
awaitTerminatedback to summary
public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException

Implements com.google.common.util.concurrent.Service.awaitTerminated.

Doc from com.google.common.util.concurrent.Service.awaitTerminated.

Waits for the Service to reach a terminal state (either terminated or failed) for no more than the given time.

Parameters
timeout:long

the maximum time to wait

unit:TimeUnit

the time unit of the timeout argument

Annotations
@Override
Exceptions
TimeoutException:
if the service has not reached the given state within the deadline
checkCurrentStateback to summary
private void checkCurrentState(Service.State expected)

Checks that the current state is equal to the expected state.

Annotations
@GuardedBy:monitor
dispatchListenerEventsback to summary
private void dispatchListenerEvents()

Attempts to execute all the listeners in listeners while not holding the monitor.

doCancelStartback to summary
protected void doCancelStart()

This method is called by stopAsync when the service is still starting (i.e. startAsync has been called but notifyStarted has not). Subclasses can override the method to cancel pending work and then call notifyStopped to stop the service.

This method should return promptly; prefer to do work on a different thread where it is convenient. It is invoked exactly once on service shutdown, even when stopAsync is called multiple times.

When this method is called state() will return State#STOPPING, which is the external state observable by the caller of stopAsync.

Annotations
@ForOverride
Since
27.0
doStartback to summary
protected abstract void doStart()

This method is called by startAsync to initiate service startup. The invocation of this method should cause a call to notifyStarted(), either during this method's run, or after it has returned. If startup fails, the invocation should cause a call to notifyFailed(Throwable) instead.

This method should return promptly; prefer to do work on a different thread where it is convenient. It is invoked exactly once on service startup, even when startAsync is called multiple times.

Annotations
@ForOverride
doStopback to summary
protected abstract void doStop()

This method should be used to initiate service shutdown. The invocation of this method should cause a call to notifyStopped(), either during this method's run, or after it has returned. If shutdown fails, the invocation should cause a call to notifyFailed(Throwable) instead.

This method should return promptly; prefer to do work on a different thread where it is convenient. It is invoked exactly once on service shutdown, even when stopAsync is called multiple times.

If stopAsync is called on a State#STARTING service, this method is not invoked immediately. Instead, it will be deferred until after the service is State#RUNNING. Services that need to cancel startup work can override doCancelStart.

Annotations
@ForOverride
enqueueFailedEventback to summary
private void enqueueFailedEvent(final Service.State from, final Throwable cause)
enqueueRunningEventback to summary
private void enqueueRunningEvent()
enqueueStartingEventback to summary
private void enqueueStartingEvent()
enqueueStoppingEventback to summary
private void enqueueStoppingEvent(final Service.State from)
enqueueTerminatedEventback to summary
private void enqueueTerminatedEvent(final Service.State from)
failureCauseback to summary
public final Throwable failureCause()

Implements com.google.common.util.concurrent.Service.failureCause.

Doc from com.google.common.util.concurrent.Service.failureCause.

Returns the Throwable that caused this service to fail.

Annotations
@Override
Since
14.0
isRunningback to summary
public final boolean isRunning()

Implements com.google.common.util.concurrent.Service.isRunning.

Doc from com.google.common.util.concurrent.Service.isRunning.

Returns true if this service is running.

Annotations
@Override
notifyFailedback to summary
protected final void notifyFailed(Throwable cause)

Invoke this method to transition the service to the State#FAILED. The service will not be stopped if it is running. Invoke this method when a service has failed critically or otherwise cannot be started nor stopped.

notifyStartedback to summary
protected final void notifyStarted()

Implementing classes should invoke this method once their service has started. It will cause the service to transition from State#STARTING to State#RUNNING.

Exceptions
IllegalStateException:
if the service is not State#STARTING.
notifyStoppedback to summary
protected final void notifyStopped()

Implementing classes should invoke this method once their service has stopped. It will cause the service to transition from State#STARTING or State#STOPPING to State#TERMINATED.

Exceptions
IllegalStateException:
if the service is not one of State#STOPPING, State#STARTING, or State#RUNNING.
startAsyncback to summary
public final Service startAsync()

Implements com.google.common.util.concurrent.Service.startAsync.

Doc from com.google.common.util.concurrent.Service.startAsync.

If the service state is State#NEW, this initiates service startup and returns immediately. A stopped service may not be restarted.

Returns:Service

this

Annotations
@CanIgnoreReturnValue
@Override
stateback to summary
public final Service.State state()

Implements com.google.common.util.concurrent.Service.state.

Doc from com.google.common.util.concurrent.Service.state.

Returns the lifecycle state of the service.

Annotations
@Override
stopAsyncback to summary
public final Service stopAsync()

Implements com.google.common.util.concurrent.Service.stopAsync.

Doc from com.google.common.util.concurrent.Service.stopAsync.

If the service is starting or running, this initiates service shutdown and returns immediately. If the service is new, it is terminated without having been started nor stopped. If the service has already been stopped, this method returns immediately without taking action.

Returns:Service

this

Annotations
@CanIgnoreReturnValue
@Override
stoppingEventback to summary
private static ListenerCallQueue.Event<Service.Listener> stoppingEvent(final Service.State from)
terminatedEventback to summary
private static ListenerCallQueue.Event<Service.Listener> terminatedEvent(final Service.State from)
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object.

Annotations
@Override
com.google.common.util.concurrent back to summary

private final Class AbstractService.HasReachedRunningGuard

extends Guard
Class Inheritance
Annotations
@WeakOuter

Field Summary

Inherited from com.google.common.util.concurrent.Monitor.Guard:
conditionmonitornextwaiterCount

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public boolean
isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition.

Constructor Detail

HasReachedRunningGuardback to summary
pack-priv HasReachedRunningGuard()

Method Detail

isSatisfiedback to summary
public boolean isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Doc from com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition. This method is always called with the associated monitor already occupied. Implementations of this method must depend only on state protected by the associated monitor, and must not modify that state.

Annotations
@Override
com.google.common.util.concurrent back to summary

private final Class AbstractService.IsStartableGuard

extends Guard
Class Inheritance
Annotations
@WeakOuter

Field Summary

Inherited from com.google.common.util.concurrent.Monitor.Guard:
conditionmonitornextwaiterCount

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public boolean
isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition.

Constructor Detail

IsStartableGuardback to summary
pack-priv IsStartableGuard()

Method Detail

isSatisfiedback to summary
public boolean isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Doc from com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition. This method is always called with the associated monitor already occupied. Implementations of this method must depend only on state protected by the associated monitor, and must not modify that state.

Annotations
@Override
com.google.common.util.concurrent back to summary

private final Class AbstractService.IsStoppableGuard

extends Guard
Class Inheritance
Annotations
@WeakOuter

Field Summary

Inherited from com.google.common.util.concurrent.Monitor.Guard:
conditionmonitornextwaiterCount

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public boolean
isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition.

Constructor Detail

IsStoppableGuardback to summary
pack-priv IsStoppableGuard()

Method Detail

isSatisfiedback to summary
public boolean isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Doc from com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition. This method is always called with the associated monitor already occupied. Implementations of this method must depend only on state protected by the associated monitor, and must not modify that state.

Annotations
@Override
com.google.common.util.concurrent back to summary

private final Class AbstractService.IsStoppedGuard

extends Guard
Class Inheritance
Annotations
@WeakOuter

Field Summary

Inherited from com.google.common.util.concurrent.Monitor.Guard:
conditionmonitornextwaiterCount

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public boolean
isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition.

Constructor Detail

IsStoppedGuardback to summary
pack-priv IsStoppedGuard()

Method Detail

isSatisfiedback to summary
public boolean isSatisfied()

Implements abstract com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Doc from com.google.common.util.concurrent.Monitor.Guard.isSatisfied.

Evaluates this guard's boolean condition. This method is always called with the associated monitor already occupied. Implementations of this method must depend only on state protected by the associated monitor, and must not modify that state.

Annotations
@Override
com.google.common.util.concurrent back to summary

private final Class AbstractService.StateSnapshot

extends Object
Class Inheritance
  • java.lang.Object
  • com.google.common.util.concurrent.AbstractService.StateSnapshot

An immutable snapshot of the current state of the service. This class represents a consistent snapshot of the state and therefore it can be used to answer simple queries without needing to grab a lock.

Field Summary

Modifier and TypeField and Description
pack-priv final Throwable
failure

The exception that caused this service to fail.

pack-priv final boolean
shutdownWhenStartupFinishes

If true, the user requested a shutdown while the service was still starting up.

pack-priv final Service.State
state

The internal state, which equals external state unless shutdownWhenStartupFinishes is true.

Constructor Summary

AccessConstructor and Description
pack-priv
StateSnapshot(Service.State internalState)

pack-priv
StateSnapshot(Service.State internalState, boolean shutdownWhenStartupFinishes, Throwable failure)

Method Summary

Modifier and TypeMethod and Description
pack-priv Service.State
pack-priv Throwable
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

failureback to summary
pack-priv final Throwable failure

The exception that caused this service to fail. This will be null unless the service has failed.

Annotations
@CheckForNull
shutdownWhenStartupFinishesback to summary
pack-priv final boolean shutdownWhenStartupFinishes

If true, the user requested a shutdown while the service was still starting up.

stateback to summary
pack-priv final Service.State state

The internal state, which equals external state unless shutdownWhenStartupFinishes is true.

Constructor Detail

StateSnapshotback to summary
pack-priv StateSnapshot(Service.State internalState)
StateSnapshotback to summary
pack-priv StateSnapshot(Service.State internalState, boolean shutdownWhenStartupFinishes, Throwable failure)

Method Detail

externalStateback to summary
pack-priv Service.State externalState()
See Also
Service#state()
failureCauseback to summary
pack-priv Throwable failureCause()
See Also
Service#failureCause()