001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.google.common.util.concurrent;
017
018import static com.google.common.base.Preconditions.checkArgument;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkState;
021import static com.google.common.base.Predicates.equalTo;
022import static com.google.common.base.Predicates.in;
023import static com.google.common.base.Predicates.instanceOf;
024import static com.google.common.base.Predicates.not;
025import static com.google.common.util.concurrent.Service.State.FAILED;
026import static com.google.common.util.concurrent.Service.State.NEW;
027import static com.google.common.util.concurrent.Service.State.RUNNING;
028import static com.google.common.util.concurrent.Service.State.STARTING;
029import static com.google.common.util.concurrent.Service.State.STOPPING;
030import static com.google.common.util.concurrent.Service.State.TERMINATED;
031import static java.util.concurrent.TimeUnit.MILLISECONDS;
032
033import com.google.common.annotations.Beta;
034import com.google.common.base.Function;
035import com.google.common.base.Objects;
036import com.google.common.base.Stopwatch;
037import com.google.common.base.Supplier;
038import com.google.common.collect.Collections2;
039import com.google.common.collect.ImmutableCollection;
040import com.google.common.collect.ImmutableList;
041import com.google.common.collect.ImmutableMap;
042import com.google.common.collect.ImmutableMultimap;
043import com.google.common.collect.ImmutableSet;
044import com.google.common.collect.ImmutableSetMultimap;
045import com.google.common.collect.Lists;
046import com.google.common.collect.Maps;
047import com.google.common.collect.Multimaps;
048import com.google.common.collect.Multiset;
049import com.google.common.collect.Ordering;
050import com.google.common.collect.SetMultimap;
051import com.google.common.collect.Sets;
052import com.google.common.util.concurrent.Service.State;
053
054import java.lang.ref.WeakReference;
055import java.util.Collection;
056import java.util.Collections;
057import java.util.EnumMap;
058import java.util.List;
059import java.util.Map;
060import java.util.Map.Entry;
061import java.util.Set;
062import java.util.concurrent.Executor;
063import java.util.concurrent.TimeUnit;
064import java.util.concurrent.TimeoutException;
065import java.util.logging.Level;
066import java.util.logging.Logger;
067
068import javax.annotation.concurrent.GuardedBy;
069import javax.annotation.concurrent.Immutable;
070
071/**
072 * A manager for monitoring and controlling a set of {@link Service services}. This class provides
073 * methods for {@linkplain #startAsync() starting}, {@linkplain #stopAsync() stopping} and
074 * {@linkplain #servicesByState inspecting} a collection of {@linkplain Service services}.
075 * Additionally, users can monitor state transitions with the {@link Listener listener} mechanism.
076 *
077 * <p>While it is recommended that service lifecycles be managed via this class, state transitions
078 * initiated via other mechanisms do not impact the correctness of its methods. For example, if the
079 * services are started by some mechanism besides {@link #startAsync}, the listeners will be invoked
080 * when appropriate and {@link #awaitHealthy} will still work as expected.
081 *
082 * <p>Here is a simple example of how to use a {@link ServiceManager} to start a server.
083 * <pre>   {@code
084 * class Server {
085 *   public static void main(String[] args) {
086 *     Set<Service> services = ...;
087 *     ServiceManager manager = new ServiceManager(services);
088 *     manager.addListener(new Listener() {
089 *         public void stopped() {}
090 *         public void healthy() {
091 *           // Services have been initialized and are healthy, start accepting requests...
092 *         }
093 *         public void failure(Service service) {
094 *           // Something failed, at this point we could log it, notify a load balancer, or take
095 *           // some other action.  For now we will just exit.
096 *           System.exit(1);
097 *         }
098 *       },
099 *       MoreExecutors.sameThreadExecutor());
100 *
101 *     Runtime.getRuntime().addShutdownHook(new Thread() {
102 *       public void run() {
103 *         // Give the services 5 seconds to stop to ensure that we are responsive to shutdown 
104 *         // requests.
105 *         try {
106 *           manager.stopAsync().awaitStopped(5, TimeUnit.SECONDS);
107 *         } catch (TimeoutException timeout) {
108 *           // stopping timed out
109 *         }
110 *       }
111 *     });
112 *     manager.startAsync();  // start all the services asynchronously
113 *   }
114 * }}</pre>
115 *
116 * <p>This class uses the ServiceManager's methods to start all of its services, to respond to
117 * service failure and to ensure that when the JVM is shutting down all the services are stopped.
118 *
119 * @author Luke Sandberg
120 * @since 14.0
121 */
122@Beta
123public final class ServiceManager {
124  private static final Logger logger = Logger.getLogger(ServiceManager.class.getName());
125  
126  /**
127   * A listener for the aggregate state changes of the services that are under management. Users
128   * that need to listen to more fine-grained events (such as when each particular
129   * {@link Service service} starts, or terminates), should attach {@link Service.Listener service
130   * listeners} to each individual service.
131   * 
132   * @author Luke Sandberg
133   * @since 15.0 (present as an interface in 14.0)
134   */
135  @Beta  // Should come out of Beta when ServiceManager does
136  public abstract static class Listener {
137    /** 
138     * Called when the service initially becomes healthy.
139     * 
140     * <p>This will be called at most once after all the services have entered the 
141     * {@linkplain State#RUNNING running} state. If any services fail during start up or 
142     * {@linkplain State#FAILED fail}/{@linkplain State#TERMINATED terminate} before all other 
143     * services have started {@linkplain State#RUNNING running} then this method will not be called.
144     */
145    public void healthy() {}
146    
147    /** 
148     * Called when the all of the component services have reached a terminal state, either 
149     * {@linkplain State#TERMINATED terminated} or {@linkplain State#FAILED failed}.
150     */
151    public void stopped() {}
152    
153    /** 
154     * Called when a component service has {@linkplain State#FAILED failed}.
155     * 
156     * @param service The service that failed.
157     */
158    public void failure(Service service) {}
159  }
160  
161  /**
162   * An encapsulation of all of the state that is accessed by the {@linkplain ServiceListener 
163   * service listeners}.  This is extracted into its own object so that {@link ServiceListener} 
164   * could be made {@code static} and its instances can be safely constructed and added in the 
165   * {@link ServiceManager} constructor without having to close over the partially constructed 
166   * {@link ServiceManager} instance (i.e. avoid leaking a pointer to {@code this}).
167   */
168  private final ServiceManagerState state;
169  private final ImmutableList<Service> services;
170  
171  /**
172   * Constructs a new instance for managing the given services.
173   * 
174   * @param services The services to manage
175   * 
176   * @throws IllegalArgumentException if not all services are {@link State#NEW new} or if there are
177   *     any duplicate services.
178   */
179  public ServiceManager(Iterable<? extends Service> services) {
180    ImmutableList<Service> copy = ImmutableList.copyOf(services);
181    if (copy.isEmpty()) {
182      // Having no services causes the manager to behave strangely. Notably, listeners are never 
183      // fired.  To avoid this we substitute a placeholder service.
184      logger.log(Level.WARNING, 
185          "ServiceManager configured with no services.  Is your application configured properly?", 
186          new EmptyServiceManagerWarning());
187      copy = ImmutableList.<Service>of(new NoOpService());
188    }
189    this.state = new ServiceManagerState(copy);
190    this.services = copy;
191    WeakReference<ServiceManagerState> stateReference = 
192        new WeakReference<ServiceManagerState>(state);
193    for (Service service : copy) {
194      // We give each listener its own SynchronizedExecutor to ensure that the state transitions
195      // are run in the same order that they occur.  The Service.Listener api guarantees us only
196      // that the transitions are submitted to the executor in the same order that they occur, so by
197      // synchronizing the executions of each listeners callbacks we can ensure that the entire
198      // execution of the listener occurs in the same order as the transitions themselves.
199      //
200      // This is necessary to prevent transitions being played back in the wrong order due to thread
201      // races to acquire the monitor in ServiceManagerState.
202      service.addListener(new ServiceListener(service, stateReference), new SynchronizedExecutor());
203      // We check the state after adding the listener as a way to ensure that our listener was added
204      // to a NEW service.
205      checkArgument(service.state() == NEW, "Can only manage NEW services, %s", service);
206    }
207    // We have installed all of our listeners and after this point any state transition should be
208    // correct.
209    this.state.markReady();
210  }
211
212  /**
213   * Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given 
214   * executor. The listener will not have previous state changes replayed, so it is 
215   * suggested that listeners are added before any of the managed services are 
216   * {@linkplain Service#start started}.
217   *
218   * <p>There is no guaranteed ordering of execution of listeners, but any listener added through 
219   * this method is guaranteed to be called whenever there is a state change.
220   *
221   * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown 
222   * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception 
223   * thrown by {@linkplain MoreExecutors#sameThreadExecutor inline execution}) will be caught and
224   * logged.
225   * 
226   * <p> For fast, lightweight listeners that would be safe to execute in any thread, consider 
227   * calling {@link #addListener(Listener)}.
228   * 
229   * @param listener the listener to run when the manager changes state
230   * @param executor the executor in which the listeners callback methods will be run.
231   */
232  public void addListener(Listener listener, Executor executor) {
233    state.addListener(listener, executor);
234  }
235
236  /**
237   * Registers a {@link Listener} to be run when this {@link ServiceManager} changes state. The 
238   * listener will not have previous state changes replayed, so it is suggested that listeners are 
239   * added before any of the managed services are {@linkplain Service#start started}.
240   *
241   * <p>There is no guaranteed ordering of execution of listeners, but any listener added through 
242   * this method is guaranteed to be called whenever there is a state change.
243   *
244   * <p>Exceptions thrown by a listener will be will be caught and logged.
245   * 
246   * @param listener the listener to run when the manager changes state
247   */
248  public void addListener(Listener listener) {
249    state.addListener(listener, MoreExecutors.sameThreadExecutor());
250  }
251
252  /**
253   * Initiates service {@linkplain Service#start startup} on all the services being managed.  It is
254   * only valid to call this method if all of the services are {@linkplain State#NEW new}.
255   * 
256   * @return this
257   * @throws IllegalStateException if any of the Services are not {@link State#NEW new} when the 
258   *     method is called.
259   */
260  public ServiceManager startAsync() {
261    for (Service service : services) {
262      State state = service.state();
263      checkState(state == NEW, "Service %s is %s, cannot start it.", service, state);
264    }
265    for (Service service : services) {
266      try {
267        service.startAsync();
268      } catch (IllegalStateException e) {
269        // This can happen if the service has already been started or stopped (e.g. by another 
270        // service or listener). Our contract says it is safe to call this method if
271        // all services were NEW when it was called, and this has already been verified above, so we
272        // don't propagate the exception.
273        logger.log(Level.WARNING, "Unable to start Service " + service, e);
274      }
275    }
276    return this;
277  }
278  
279  /**
280   * Waits for the {@link ServiceManager} to become {@linkplain #isHealthy() healthy}.  The manager
281   * will become healthy after all the component services have reached the {@linkplain State#RUNNING
282   * running} state.  
283   * 
284   * @throws IllegalStateException if the service manager reaches a state from which it cannot 
285   *     become {@linkplain #isHealthy() healthy}.
286   */
287  public void awaitHealthy() {
288    state.awaitHealthy();
289  }
290  
291  /**
292   * Waits for the {@link ServiceManager} to become {@linkplain #isHealthy() healthy} for no more 
293   * than the given time.  The manager will become healthy after all the component services have 
294   * reached the {@linkplain State#RUNNING running} state. 
295   *
296   * @param timeout the maximum time to wait
297   * @param unit the time unit of the timeout argument
298   * @throws TimeoutException if not all of the services have finished starting within the deadline
299   * @throws IllegalStateException if the service manager reaches a state from which it cannot 
300   *     become {@linkplain #isHealthy() healthy}.
301   */
302  public void awaitHealthy(long timeout, TimeUnit unit) throws TimeoutException {
303    state.awaitHealthy(timeout, unit);
304  }
305
306  /**
307   * Initiates service {@linkplain Service#stop shutdown} if necessary on all the services being 
308   * managed. 
309   *    
310   * @return this
311   */
312  public ServiceManager stopAsync() {
313    for (Service service : services) {
314      service.stopAsync();
315    }
316    return this;
317  }
318 
319  /**
320   * Waits for the all the services to reach a terminal state. After this method returns all
321   * services will either be {@link Service.State#TERMINATED terminated} or 
322   * {@link Service.State#FAILED failed}
323   */
324  public void awaitStopped() {
325    state.awaitStopped();
326  }
327  
328  /**
329   * Waits for the all the services to reach a terminal state for no more than the given time. After
330   * this method returns all services will either be {@link Service.State#TERMINATED terminated} or 
331   * {@link Service.State#FAILED failed}
332   *
333   * @param timeout the maximum time to wait
334   * @param unit the time unit of the timeout argument
335   * @throws TimeoutException if not all of the services have stopped within the deadline
336   */
337  public void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException {
338    state.awaitStopped(timeout, unit);
339  }
340  
341  /**
342   * Returns true if all services are currently in the {@linkplain State#RUNNING running} state.  
343   * 
344   * <p>Users who want more detailed information should use the {@link #servicesByState} method to 
345   * get detailed information about which services are not running.
346   */
347  public boolean isHealthy() {
348    for (Service service : services) {
349      if (!service.isRunning()) {
350        return false;
351      }
352    }
353    return true;
354  }
355  
356  /**
357   * Provides a snapshot of the current state of all the services under management.
358   *
359   * <p>N.B. This snapshot is guaranteed to be consistent, i.e. the set of states returned will
360   * correspond to a point in time view of the services.
361   */
362  public ImmutableMultimap<State, Service> servicesByState() {
363    return state.servicesByState();
364  }
365  
366  /**
367   * Returns the service load times. This value will only return startup times for services that
368   * have finished starting.
369   *
370   * @return Map of services and their corresponding startup time in millis, the map entries will be
371   *     ordered by startup time.
372   */
373  public ImmutableMap<Service, Long> startupTimes() {
374    return state.startupTimes();
375  }
376  
377  @Override public String toString() {
378    return Objects.toStringHelper(ServiceManager.class)
379        .add("services", Collections2.filter(services, not(instanceOf(NoOpService.class))))
380        .toString();
381  }
382  
383  /**
384   * An encapsulation of all the mutable state of the {@link ServiceManager} that needs to be 
385   * accessed by instances of {@link ServiceListener}.
386   */
387  private static final class ServiceManagerState {
388    final Monitor monitor = new Monitor();
389
390    @GuardedBy("monitor")
391    final SetMultimap<State, Service> servicesByState =
392        Multimaps.newSetMultimap(new EnumMap<State, Collection<Service>>(State.class),
393            new Supplier<Set<Service>>() {
394              @Override public Set<Service> get() {
395                return Sets.newLinkedHashSet();
396              }
397            });
398
399    @GuardedBy("monitor")
400    final Multiset<State> states = servicesByState.keys();
401
402    @GuardedBy("monitor")
403    final Map<Service, Stopwatch> startupTimers = Maps.newIdentityHashMap();
404
405    /**
406     * These two booleans are used to mark the state as ready to start.
407     * {@link #ready}: is set by {@link #markReady} to indicate that all listeners have been 
408     *     correctly installed
409     * {@link #transitioned}: is set by {@link #transitionService} to indicate that some transition 
410     *     has been performed.
411     * 
412     * <p>Together, they allow us to enforce that all services have their listeners installed prior
413     * to any service performing a transition, then we can fail in the ServiceManager constructor
414     * rather than in a Service.Listener callback.
415     */
416    @GuardedBy("monitor")
417    boolean ready;
418    
419    @GuardedBy("monitor")
420    boolean transitioned;
421    
422    final int numberOfServices;
423
424    /**
425     * Controls how long to wait for all the services to either become healthy or reach a
426     * state from which it is guaranteed that it can never become healthy.
427     */
428    final Monitor.Guard awaitHealthGuard = new Monitor.Guard(monitor) {
429      @Override public boolean isSatisfied() {
430        // All services have started or some service has terminated/failed.
431        return states.count(RUNNING) == numberOfServices
432            || states.contains(STOPPING) 
433            || states.contains(TERMINATED) 
434            || states.contains(FAILED);
435      }
436    };
437
438    /**
439     * Controls how long to wait for all services to reach a terminal state.
440     */
441    final Monitor.Guard stoppedGuard = new Monitor.Guard(monitor) {
442      @Override public boolean isSatisfied() {
443        return states.count(TERMINATED) + states.count(FAILED) == numberOfServices;
444      }
445    };
446
447    /** The listeners to notify during a state transition. */
448    @GuardedBy("monitor")
449    final List<ListenerExecutorPair> listeners = Lists.newArrayList();
450
451    /**
452     * The queue of listeners that are waiting to be executed.
453     *
454     * <p>Enqueue operations should be protected by {@link #monitor} while dequeue operations are
455     * not protected. Holding {@link #monitor} while enqueuing ensures that listeners in the queue
456     * are in the correct order and {@link ExecutionQueue} ensures that they are executed in the
457     * correct order.
458     */
459    @GuardedBy("monitor")
460    final ExecutionQueue queuedListeners = new ExecutionQueue();
461    
462    /**
463     * It is implicitly assumed that all the services are NEW and that they will all remain NEW 
464     * until all the Listeners are installed and {@link #markReady()} is called.  It is our caller's
465     * responsibility to only call {@link #markReady()} if all services were new at the time this
466     * method was called and when all the listeners were installed.
467     */
468    ServiceManagerState(ImmutableCollection<Service> services) {
469      this.numberOfServices = services.size();
470      servicesByState.putAll(NEW, services);
471      for (Service service : services) {
472        startupTimers.put(service, Stopwatch.createUnstarted());
473      }
474    }
475
476    /**
477     * Marks the {@link State} as ready to receive transitions. Returns true if no transitions have
478     * been observed yet.
479     */
480    void markReady() {
481      monitor.enter();
482      try {
483        if (!transitioned) {
484          // nothing has transitioned since construction, good.
485          ready = true;
486        } else {
487          // This should be an extremely rare race condition.
488          List<Service> servicesInBadStates = Lists.newArrayList();
489          for (Service service : servicesByState().values()) {
490            if (service.state() != NEW) {
491              servicesInBadStates.add(service);
492            }
493          }
494          throw new IllegalArgumentException("Services started transitioning asynchronously before "
495              + "the ServiceManager was constructed: " + servicesInBadStates);
496        }
497      } finally {
498        monitor.leave();
499      }
500    }
501
502    void addListener(Listener listener, Executor executor) {
503      checkNotNull(listener, "listener");
504      checkNotNull(executor, "executor");
505      monitor.enter();
506      try {
507        // no point in adding a listener that will never be called
508        if (!stoppedGuard.isSatisfied()) {
509          listeners.add(new ListenerExecutorPair(listener, executor));
510        }
511      } finally {
512        monitor.leave();
513      }
514    }
515    
516    void awaitHealthy() {
517      monitor.enterWhenUninterruptibly(awaitHealthGuard);
518      try {
519        checkHealthy();
520      } finally {
521        monitor.leave();
522      }
523    }
524
525    void awaitHealthy(long timeout, TimeUnit unit) throws TimeoutException {
526      monitor.enter();
527      try {
528        if (!monitor.waitForUninterruptibly(awaitHealthGuard, timeout, unit)) {
529          throw new TimeoutException("Timeout waiting for the services to become healthy. The "
530              + "following services have not started: " 
531              + Multimaps.filterKeys(servicesByState, in(ImmutableSet.of(NEW, STARTING))));
532        }
533        checkHealthy();
534      } finally {
535        monitor.leave();
536      }
537    }
538    
539    void awaitStopped() {
540      monitor.enterWhenUninterruptibly(stoppedGuard);
541      monitor.leave();
542    }
543    
544    void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException {
545      monitor.enter();
546      try {
547        if (!monitor.waitForUninterruptibly(stoppedGuard, timeout, unit)) {
548          throw new TimeoutException("Timeout waiting for the services to stop. The following "
549              + "services have not stopped: " 
550              + Multimaps.filterKeys(servicesByState, 
551                  not(in(ImmutableSet.of(TERMINATED, FAILED))))); 
552        }
553      } finally {
554        monitor.leave();
555      }
556    }
557
558    ImmutableMultimap<State, Service> servicesByState() {
559      ImmutableSetMultimap.Builder<State, Service> builder = ImmutableSetMultimap.builder();
560      monitor.enter();
561      try {
562        for (Entry<State, Service> entry : servicesByState.entries()) {
563          if (!(entry.getValue() instanceof NoOpService)) {
564            builder.put(entry.getKey(), entry.getValue());
565          }
566        }
567      } finally {
568        monitor.leave();
569      }
570      return builder.build();
571    }
572    
573    ImmutableMap<Service, Long> startupTimes() {
574      List<Entry<Service, Long>> loadTimes;
575      monitor.enter();
576      try {
577        loadTimes = Lists.newArrayListWithCapacity(
578            states.size() - states.count(NEW) + states.count(STARTING));
579        for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
580          Service service = entry.getKey();
581          Stopwatch stopWatch = entry.getValue();
582          // N.B. we check the service state in the multimap rather than via Service.state() because
583          // the multimap is guaranteed to be in sync with our timers while the Service.state() is
584          // not.  Due to happens-before ness of the monitor this 'weirdness' will not be observable
585          // by our caller.
586          if (!stopWatch.isRunning() && !servicesByState.containsEntry(NEW, service) 
587              && !(service instanceof NoOpService)) {
588            loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
589          }
590        }
591      } finally {
592        monitor.leave();
593      }
594      Collections.sort(loadTimes, Ordering.<Long>natural()
595          .onResultOf(new Function<Entry<Service, Long>, Long>() {
596            @Override public Long apply(Map.Entry<Service, Long> input) {
597              return input.getValue();
598            }
599          }));
600      ImmutableMap.Builder<Service, Long> builder = ImmutableMap.builder();
601      for (Entry<Service, Long> entry : loadTimes) {
602        builder.put(entry);
603      }
604      return builder.build();
605    }
606    
607    /** 
608     * Updates the state with the given service transition.
609     * 
610     * <p>This method performs the main logic of ServiceManager in the following steps.
611     * <ol>
612     *      <li>Update the {@link #servicesByState()}
613     *      <li>Update the {@link #startupTimers}
614     *      <li>Based on the new state queue listeners to run
615     *      <li>Run the listeners (outside of the lock)
616     * </ol>
617     */
618    void transitionService(final Service service, State from, State to) {
619      checkNotNull(service);
620      checkArgument(from != to);
621      monitor.enter();
622      try {
623        transitioned = true;
624        if (!ready) {
625          return;
626        }
627        // Update state.
628        checkState(servicesByState.remove(from, service),
629            "Service %s not at the expected location in the state map %s", service, from);
630        checkState(servicesByState.put(to, service),
631            "Service %s in the state map unexpectedly at %s", service, to);
632        // Update the timer
633        Stopwatch stopwatch = startupTimers.get(service);
634        if (from == NEW) {
635          stopwatch.start();
636        }
637        if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
638          // N.B. if we miss the STARTING event then we will never record a startup time.
639          stopwatch.stop();
640          if (!(service instanceof NoOpService)) {
641            logger.log(Level.FINE, "Started {0} in {1}.",
642                new Object[] {service, stopwatch});
643          }
644        }
645        // Queue our listeners
646        
647        // Did a service fail?
648        if (to == FAILED) {
649          fireFailedListeners(service);
650        }
651        
652        if (states.count(RUNNING) == numberOfServices) {
653          // This means that the manager is currently healthy. N.B. If other threads call isHealthy 
654          // they are not guaranteed to get 'true', because any service could fail right now. 
655          fireHealthyListeners();
656        } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
657          fireStoppedListeners();
658          // no more listeners could possibly be called, so clear them out to save some memory.
659          listeners.clear();
660        }
661      } finally {
662        monitor.leave();
663        // Run our executors outside of the lock
664        executeListeners();
665      }
666    }
667
668    @GuardedBy("monitor")
669    void fireStoppedListeners() {
670      for (final ListenerExecutorPair pair : listeners) {
671        queuedListeners.add(new Runnable() {
672          @Override public void run() {
673            pair.listener.stopped();
674          }
675        }, pair.executor);
676      }
677    }
678
679    @GuardedBy("monitor")
680    void fireHealthyListeners() {
681      for (final ListenerExecutorPair pair : listeners) {
682        queuedListeners.add(new Runnable() {
683          @Override public void run() {
684            pair.listener.healthy();
685          }
686        }, pair.executor);
687      }
688    }
689
690    @GuardedBy("monitor")
691    void fireFailedListeners(final Service service) {
692      for (final ListenerExecutorPair pair : listeners) {
693        queuedListeners.add(new Runnable() {
694          @Override public void run() {
695            pair.listener.failure(service);
696          }
697        }, pair.executor);
698      }
699    }
700
701    /** Attempts to execute all the listeners in {@link #queuedListeners}. */
702    void executeListeners() {
703      checkState(!monitor.isOccupiedByCurrentThread(), 
704          "It is incorrect to execute listeners with the monitor held.");
705      queuedListeners.execute();
706    }
707
708    @GuardedBy("monitor")
709    void checkHealthy() {
710      if (states.count(RUNNING) != numberOfServices) {
711        throw new IllegalStateException("Expected to be healthy after starting. "
712            + "The following services are not running: " + 
713            Multimaps.filterKeys(servicesByState, not(equalTo(RUNNING))));
714      }
715    }
716  }
717
718  /**
719   * A {@link Service} that wraps another service and times how long it takes for it to start and
720   * also calls the {@link ServiceManagerState#transitionService(Service, State, State)},
721   * to record the state transitions.
722   */
723  private static final class ServiceListener extends Service.Listener {
724    final Service service;
725    // We store the state in a weak reference to ensure that if something went wrong while 
726    // constructing the ServiceManager we don't pointlessly keep updating the state.
727    final WeakReference<ServiceManagerState> state;
728    
729    ServiceListener(Service service, WeakReference<ServiceManagerState> state) {
730      this.service = service;
731      this.state = state;
732    }
733    
734    @Override public void starting() {
735      ServiceManagerState state = this.state.get();
736      if (state != null) {
737        state.transitionService(service, NEW, STARTING);
738        if (!(service instanceof NoOpService)) {
739          logger.log(Level.FINE, "Starting {0}.", service);
740        }
741      }
742    }
743
744    @Override public void running() {
745      ServiceManagerState state = this.state.get();
746      if (state != null) {
747        state.transitionService(service, STARTING, RUNNING);
748      }
749    }
750    
751    @Override public void stopping(State from) {
752      ServiceManagerState state = this.state.get();
753      if (state != null) {
754        state.transitionService(service, from, STOPPING);
755      }
756    }
757    
758    @Override public void terminated(State from) {
759      ServiceManagerState state = this.state.get();
760      if (state != null) {
761        if (!(service instanceof NoOpService)) {
762          logger.log(Level.FINE, "Service {0} has terminated. Previous state was: {1}", 
763              new Object[] {service, from});
764        }
765        state.transitionService(service, from, TERMINATED);
766      }
767    }
768    
769    @Override public void failed(State from, Throwable failure) {
770      ServiceManagerState state = this.state.get();
771      if (state != null) {
772        // Log before the transition, so that if the process exits in response to server failure,
773        // there is a higher likelihood that the cause will be in the logs.
774        if (!(service instanceof NoOpService)) {
775          logger.log(Level.SEVERE, "Service " + service + " has failed in the " + from + " state.",
776              failure);
777        }
778        state.transitionService(service, from, FAILED);
779      }
780    }
781  }
782  
783  /** Simple value object binding a listener to its executor. */
784  @Immutable private static final class ListenerExecutorPair {
785    final Listener listener;
786    final Executor executor;
787    
788    ListenerExecutorPair(Listener listener, Executor executor) {
789      this.listener = listener;
790      this.executor = executor;
791    }
792  }
793  
794  /**
795   * A {@link Service} instance that does nothing.  This is only useful as a placeholder to
796   * ensure that the {@link ServiceManager} functions properly even when it is managing no services.
797   * 
798   * <p>The use of this class is considered an implementation detail of ServiceManager and as such
799   * it is excluded from {@link #servicesByState}, {@link #startupTimes}, {@link #toString} and all
800   * logging statements.
801   */
802  private static final class NoOpService extends AbstractService {
803    @Override protected void doStart() { notifyStarted(); }
804    @Override protected void doStop() { notifyStopped(); }
805  }
806  
807  /** This is never thrown but only used for logging. */
808  private static final class EmptyServiceManagerWarning extends Throwable {}
809  
810  /** 
811   * A same-thread executor that executes all the runnables from within a synchronized block.
812   * 
813   * <p>This ensures that tasks submitted to the executor run in the same order that they were 
814   * submitted.
815   */
816  private static final class SynchronizedExecutor implements Executor {
817    @Override public synchronized void execute(Runnable command) {
818      command.run();
819    }
820  }
821}