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