001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import com.google.common.annotations.Beta;
018import com.google.common.annotations.GwtIncompatible;
019import com.google.errorprone.annotations.CanIgnoreReturnValue;
020import java.util.concurrent.Executor;
021import java.util.concurrent.TimeUnit;
022import java.util.concurrent.TimeoutException;
023
024/**
025 * An object with an operational state, plus asynchronous {@link #startAsync()} and {@link
026 * #stopAsync()} lifecycle methods to transition between states. Example services include
027 * webservers, RPC servers and timers.
028 *
029 * <p>The normal lifecycle of a service is:
030 *
031 * <ul>
032 *   <li>{@linkplain State#NEW NEW} -&gt;
033 *   <li>{@linkplain State#STARTING STARTING} -&gt;
034 *   <li>{@linkplain State#RUNNING RUNNING} -&gt;
035 *   <li>{@linkplain State#STOPPING STOPPING} -&gt;
036 *   <li>{@linkplain State#TERMINATED TERMINATED}
037 * </ul>
038 *
039 * <p>There are deviations from this if there are failures or if {@link Service#stopAsync} is called
040 * before the {@link Service} reaches the {@linkplain State#RUNNING RUNNING} state. The set of legal
041 * transitions form a <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">DAG</a>,
042 * therefore every method of the listener will be called at most once. N.B. The {@link State#FAILED}
043 * and {@link State#TERMINATED} states are terminal states, once a service enters either of these
044 * states it cannot ever leave them.
045 *
046 * <p>Implementors of this interface are strongly encouraged to extend one of the abstract classes
047 * in this package which implement this interface and make the threading and state management
048 * easier.
049 *
050 * @author Jesse Wilson
051 * @author Luke Sandberg
052 * @since 9.0 (in 1.0 as {@code com.google.common.base.Service})
053 */
054@Beta
055@GwtIncompatible
056public interface Service {
057  /**
058   * If the service state is {@link State#NEW}, this initiates service startup and returns
059   * immediately. A stopped service may not be restarted.
060   *
061   * @return this
062   * @throws IllegalStateException if the service is not {@link State#NEW}
063   * @since 15.0
064   */
065  @CanIgnoreReturnValue
066  Service startAsync();
067
068  /** Returns {@code true} if this service is {@linkplain State#RUNNING running}. */
069  boolean isRunning();
070
071  /** Returns the lifecycle state of the service. */
072  State state();
073
074  /**
075   * If the service is {@linkplain State#STARTING starting} or {@linkplain State#RUNNING running},
076   * this initiates service shutdown and returns immediately. If the service is {@linkplain
077   * State#NEW new}, it is {@linkplain State#TERMINATED terminated} without having been started nor
078   * stopped. If the service has already been stopped, this method returns immediately without
079   * taking action.
080   *
081   * @return this
082   * @since 15.0
083   */
084  @CanIgnoreReturnValue
085  Service stopAsync();
086
087  /**
088   * Waits for the {@link Service} to reach the {@linkplain State#RUNNING running state}.
089   *
090   * @throws IllegalStateException if the service reaches a state from which it is not possible to
091   *     enter the {@link State#RUNNING} state. e.g. if the {@code state} is {@code
092   *     State#TERMINATED} when this method is called then this will throw an IllegalStateException.
093   * @since 15.0
094   */
095  void awaitRunning();
096
097  /**
098   * Waits for the {@link Service} to reach the {@linkplain State#RUNNING running state} for no more
099   * than the given time.
100   *
101   * @param timeout the maximum time to wait
102   * @param unit the time unit of the timeout argument
103   * @throws TimeoutException if the service has not reached the given state within the deadline
104   * @throws IllegalStateException if the service reaches a state from which it is not possible to
105   *     enter the {@link State#RUNNING RUNNING} state. e.g. if the {@code state} is {@code
106   *     State#TERMINATED} when this method is called then this will throw an IllegalStateException.
107   * @since 15.0
108   */
109  void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException;
110
111  /**
112   * Waits for the {@link Service} to reach the {@linkplain State#TERMINATED terminated state}.
113   *
114   * @throws IllegalStateException if the service {@linkplain State#FAILED fails}.
115   * @since 15.0
116   */
117  void awaitTerminated();
118
119  /**
120   * Waits for the {@link Service} to reach a terminal state (either {@link Service.State#TERMINATED
121   * terminated} or {@link Service.State#FAILED failed}) for no more than the given time.
122   *
123   * @param timeout the maximum time to wait
124   * @param unit the time unit of the timeout argument
125   * @throws TimeoutException if the service has not reached the given state within the deadline
126   * @throws IllegalStateException if the service {@linkplain State#FAILED fails}.
127   * @since 15.0
128   */
129  void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException;
130
131  /**
132   * Returns the {@link Throwable} that caused this service to fail.
133   *
134   * @throws IllegalStateException if this service's state isn't {@linkplain State#FAILED FAILED}.
135   * @since 14.0
136   */
137  Throwable failureCause();
138
139  /**
140   * Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given
141   * executor. The listener will have the corresponding transition method called whenever the
142   * service changes state. The listener will not have previous state changes replayed, so it is
143   * suggested that listeners are added before the service starts.
144   *
145   * <p>{@code addListener} guarantees execution ordering across calls to a given listener but not
146   * across calls to multiple listeners. Specifically, a given listener will have its callbacks
147   * invoked in the same order as the underlying service enters those states. Additionally, at most
148   * one of the listener's callbacks will execute at once. However, multiple listeners' callbacks
149   * may execute concurrently, and listeners may execute in an order different from the one in which
150   * they were registered.
151   *
152   * <p>RuntimeExceptions thrown by a listener will be caught and logged. Any exception thrown
153   * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException}) will be caught and
154   * logged.
155   *
156   * @param listener the listener to run when the service changes state is complete
157   * @param executor the executor in which the listeners callback methods will be run. For fast,
158   *     lightweight listeners that would be safe to execute in any thread, consider {@link
159   *     MoreExecutors#directExecutor}.
160   * @since 13.0
161   */
162  void addListener(Listener listener, Executor executor);
163
164  /**
165   * The lifecycle states of a service.
166   *
167   * <p>The ordering of the {@link State} enum is defined such that if there is a state transition
168   * from {@code A -> B} then {@code A.compareTo(B) < 0}. N.B. The converse is not true, i.e. if
169   * {@code A.compareTo(B) < 0} then there is <b>not</b> guaranteed to be a valid state transition
170   * {@code A -> B}.
171   *
172   * @since 9.0 (in 1.0 as {@code com.google.common.base.Service.State})
173   */
174  @Beta // should come out of Beta when Service does
175  enum State {
176    /** A service in this state is inactive. It does minimal work and consumes minimal resources. */
177    NEW {
178      @Override
179      boolean isTerminal() {
180        return false;
181      }
182    },
183
184    /** A service in this state is transitioning to {@link #RUNNING}. */
185    STARTING {
186      @Override
187      boolean isTerminal() {
188        return false;
189      }
190    },
191
192    /** A service in this state is operational. */
193    RUNNING {
194      @Override
195      boolean isTerminal() {
196        return false;
197      }
198    },
199
200    /** A service in this state is transitioning to {@link #TERMINATED}. */
201    STOPPING {
202      @Override
203      boolean isTerminal() {
204        return false;
205      }
206    },
207
208    /**
209     * A service in this state has completed execution normally. It does minimal work and consumes
210     * minimal resources.
211     */
212    TERMINATED {
213      @Override
214      boolean isTerminal() {
215        return true;
216      }
217    },
218
219    /**
220     * A service in this state has encountered a problem and may not be operational. It cannot be
221     * started nor stopped.
222     */
223    FAILED {
224      @Override
225      boolean isTerminal() {
226        return true;
227      }
228    };
229
230    /** Returns true if this state is terminal. */
231    abstract boolean isTerminal();
232  }
233
234  /**
235   * A listener for the various state changes that a {@link Service} goes through in its lifecycle.
236   *
237   * <p>All methods are no-ops by default, implementors should override the ones they care about.
238   *
239   * @author Luke Sandberg
240   * @since 15.0 (present as an interface in 13.0)
241   */
242  @Beta // should come out of Beta when Service does
243  abstract class Listener {
244    /**
245     * Called when the service transitions from {@linkplain State#NEW NEW} to {@linkplain
246     * State#STARTING STARTING}. This occurs when {@link Service#startAsync} is called the first
247     * time.
248     */
249    public void starting() {}
250
251    /**
252     * Called when the service transitions from {@linkplain State#STARTING STARTING} to {@linkplain
253     * State#RUNNING RUNNING}. This occurs when a service has successfully started.
254     */
255    public void running() {}
256
257    /**
258     * Called when the service transitions to the {@linkplain State#STOPPING STOPPING} state. The
259     * only valid values for {@code from} are {@linkplain State#STARTING STARTING} or {@linkplain
260     * State#RUNNING RUNNING}. This occurs when {@link Service#stopAsync} is called.
261     *
262     * @param from The previous state that is being transitioned from.
263     */
264    public void stopping(State from) {}
265
266    /**
267     * Called when the service transitions to the {@linkplain State#TERMINATED TERMINATED} state.
268     * The {@linkplain State#TERMINATED TERMINATED} state is a terminal state in the transition
269     * diagram. Therefore, if this method is called, no other methods will be called on the {@link
270     * Listener}.
271     *
272     * @param from The previous state that is being transitioned from. The only valid values for
273     *     this are {@linkplain State#NEW NEW}, {@linkplain State#RUNNING RUNNING} or {@linkplain
274     *     State#STOPPING STOPPING}.
275     */
276    public void terminated(State from) {}
277
278    /**
279     * Called when the service transitions to the {@linkplain State#FAILED FAILED} state. The
280     * {@linkplain State#FAILED FAILED} state is a terminal state in the transition diagram.
281     * Therefore, if this method is called, no other methods will be called on the {@link Listener}.
282     *
283     * @param from The previous state that is being transitioned from. Failure can occur in any
284     *     state with the exception of {@linkplain State#NEW NEW} or {@linkplain State#TERMINATED
285     *     TERMINATED}.
286     * @param failure The exception that caused the failure.
287     */
288    public void failed(State from, Throwable failure) {}
289  }
290}