1/*
2 * Copyright (C) 2009 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.util.concurrent;
18
19import com.google.common.annotations.Beta;
20import com.google.common.base.Throwables;
21
22import java.util.concurrent.Executor;
23import java.util.logging.Level;
24import java.util.logging.Logger;
25
26/**
27 * Base class for services that can implement {@link #startUp}, {@link #run} and
28 * {@link #shutDown} methods. This class uses a single thread to execute the
29 * service; consider {@link AbstractService} if you would like to manage any
30 * threading manually.
31 *
32 * @author Jesse Wilson
33 * @since 1.0
34 */
35@Beta
36public abstract class AbstractExecutionThreadService implements Service {
37  private static final Logger logger = Logger.getLogger(
38      AbstractExecutionThreadService.class.getName());
39
40  /* use AbstractService for state management */
41  private final Service delegate = new AbstractService() {
42    @Override protected final void doStart() {
43      executor().execute(new Runnable() {
44        @Override
45        public void run() {
46          try {
47            startUp();
48            notifyStarted();
49
50            if (isRunning()) {
51              try {
52                AbstractExecutionThreadService.this.run();
53              } catch (Throwable t) {
54                try {
55                  shutDown();
56                } catch (Exception ignored) {
57                  logger.log(Level.WARNING,
58                      "Error while attempting to shut down the service after failure.", ignored);
59                }
60                throw t;
61              }
62            }
63
64            shutDown();
65            notifyStopped();
66          } catch (Throwable t) {
67            notifyFailed(t);
68            throw Throwables.propagate(t);
69          }
70        }
71      });
72    }
73
74    @Override protected void doStop() {
75      triggerShutdown();
76    }
77  };
78
79  /**
80   * Start the service. This method is invoked on the execution thread.
81   */
82  protected void startUp() throws Exception {}
83
84  /**
85   * Run the service. This method is invoked on the execution thread.
86   * Implementations must respond to stop requests. You could poll for lifecycle
87   * changes in a work loop:
88   * <pre>
89   *   public void run() {
90   *     while ({@link #isRunning()}) {
91   *       // perform a unit of work
92   *     }
93   *   }
94   * </pre>
95   * ...or you could respond to stop requests by implementing {@link
96   * #triggerShutdown()}, which should cause {@link #run()} to return.
97   */
98  protected abstract void run() throws Exception;
99
100  /**
101   * Stop the service. This method is invoked on the execution thread.
102   */
103  // TODO: consider supporting a TearDownTestCase-like API
104  protected void shutDown() throws Exception {}
105
106  /**
107   * Invoked to request the service to stop.
108   */
109  protected void triggerShutdown() {}
110
111  /**
112   * Returns the {@link Executor} that will be used to run this service.
113   * Subclasses may override this method to use a custom {@link Executor}, which
114   * may configure its worker thread with a specific name, thread group or
115   * priority. The returned executor's {@link Executor#execute(Runnable)
116   * execute()} method is called when this service is started, and should return
117   * promptly.
118   *
119   * <p>The default implementation returns a new {@link Executor} that sets the
120   * name of its threads to the string returned by {@link #getServiceName}
121   */
122  protected Executor executor() {
123    return new Executor() {
124      @Override
125      public void execute(Runnable command) {
126        new Thread(command, getServiceName()).start();
127      }
128    };
129  }
130
131  @Override public String toString() {
132    return getServiceName() + " [" + state() + "]";
133  }
134
135  // We override instead of using ForwardingService so that these can be final.
136
137  @Override public final ListenableFuture<State> start() {
138    return delegate.start();
139  }
140
141  @Override public final State startAndWait() {
142    return delegate.startAndWait();
143  }
144
145  @Override public final boolean isRunning() {
146    return delegate.isRunning();
147  }
148
149  @Override public final State state() {
150    return delegate.state();
151  }
152
153  @Override public final ListenableFuture<State> stop() {
154    return delegate.stop();
155  }
156
157  @Override public final State stopAndWait() {
158    return delegate.stopAndWait();
159  }
160
161  /**
162   * Returns the name of this service. {@link AbstractExecutionThreadService} may include the name
163   * in debugging output.
164   *
165   * <p>Subclasses may override this method.
166   *
167   * @since 10.0
168   */
169  protected String getServiceName() {
170    return getClass().getSimpleName();
171  }
172}
173