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.base.Supplier;
019import com.google.errorprone.annotations.CanIgnoreReturnValue;
020import com.google.j2objc.annotations.WeakOuter;
021import java.util.concurrent.Executor;
022import java.util.concurrent.TimeUnit;
023import java.util.concurrent.TimeoutException;
024
025/**
026 * Base class for services that do not need a thread while "running" but may need one during startup
027 * and shutdown. Subclasses can implement {@link #startUp} and {@link #shutDown} methods, each which
028 * run in a executor which by default uses a separate thread for each method.
029 *
030 * @author Chris Nokleberg
031 * @since 1.0
032 */
033@GwtIncompatible
034public abstract class AbstractIdleService implements Service {
035
036  /* Thread names will look like {@code "MyService STARTING"}. */
037  private final Supplier<String> threadNameSupplier = new ThreadNameSupplier();
038
039  @WeakOuter
040  private final class ThreadNameSupplier implements Supplier<String> {
041    @Override
042    public String get() {
043      return serviceName() + " " + state();
044    }
045  }
046
047  /* use AbstractService for state management */
048  private final Service delegate = new DelegateService();
049
050  @WeakOuter
051  private final class DelegateService extends AbstractService {
052    @Override
053    protected final void doStart() {
054      MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
055          .execute(
056              new Runnable() {
057                @Override
058                public void run() {
059                  try {
060                    startUp();
061                    notifyStarted();
062                  } catch (Throwable t) {
063                    notifyFailed(t);
064                  }
065                }
066              });
067    }
068
069    @Override
070    protected final void doStop() {
071      MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
072          .execute(
073              new Runnable() {
074                @Override
075                public void run() {
076                  try {
077                    shutDown();
078                    notifyStopped();
079                  } catch (Throwable t) {
080                    notifyFailed(t);
081                  }
082                }
083              });
084    }
085
086    @Override
087    public String toString() {
088      return AbstractIdleService.this.toString();
089    }
090  }
091
092  /** Constructor for use by subclasses. */
093  protected AbstractIdleService() {}
094
095  /** Start the service. */
096  protected abstract void startUp() throws Exception;
097
098  /** Stop the service. */
099  protected abstract void shutDown() throws Exception;
100
101  /**
102   * Returns the {@link Executor} that will be used to run this service. Subclasses may override
103   * this method to use a custom {@link Executor}, which may configure its worker thread with a
104   * specific name, thread group or priority. The returned executor's {@link
105   * Executor#execute(Runnable) execute()} method is called when this service is started and
106   * stopped, and should return promptly.
107   */
108  protected Executor executor() {
109    return new Executor() {
110      @Override
111      public void execute(Runnable command) {
112        MoreExecutors.newThread(threadNameSupplier.get(), command).start();
113      }
114    };
115  }
116
117  @Override
118  public String toString() {
119    return serviceName() + " [" + state() + "]";
120  }
121
122  @Override
123  public final boolean isRunning() {
124    return delegate.isRunning();
125  }
126
127  @Override
128  public final State state() {
129    return delegate.state();
130  }
131
132  /** @since 13.0 */
133  @Override
134  public final void addListener(Listener listener, Executor executor) {
135    delegate.addListener(listener, executor);
136  }
137
138  /** @since 14.0 */
139  @Override
140  public final Throwable failureCause() {
141    return delegate.failureCause();
142  }
143
144  /** @since 15.0 */
145  @CanIgnoreReturnValue
146  @Override
147  public final Service startAsync() {
148    delegate.startAsync();
149    return this;
150  }
151
152  /** @since 15.0 */
153  @CanIgnoreReturnValue
154  @Override
155  public final Service stopAsync() {
156    delegate.stopAsync();
157    return this;
158  }
159
160  /** @since 15.0 */
161  @Override
162  public final void awaitRunning() {
163    delegate.awaitRunning();
164  }
165
166  /** @since 15.0 */
167  @Override
168  public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException {
169    delegate.awaitRunning(timeout, unit);
170  }
171
172  /** @since 15.0 */
173  @Override
174  public final void awaitTerminated() {
175    delegate.awaitTerminated();
176  }
177
178  /** @since 15.0 */
179  @Override
180  public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
181    delegate.awaitTerminated(timeout, unit);
182  }
183
184  /**
185   * Returns the name of this service. {@link AbstractIdleService} may include the name in debugging
186   * output.
187   *
188   * @since 14.0
189   */
190  protected String serviceName() {
191    return getClass().getSimpleName();
192  }
193}