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