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