001 /*
002 * Copyright (C) 2009 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 */
016
017 package com.google.common.util.concurrent;
018
019 import com.google.common.annotations.Beta;
020 import com.google.common.base.Throwables;
021
022 import java.util.concurrent.Executor;
023
024 /**
025 * Base class for services that can implement {@link #startUp}, {@link #run} and
026 * {@link #shutDown} methods. This class uses a single thread to execute the
027 * service; consider {@link AbstractService} if you would like to manage any
028 * threading manually.
029 *
030 * @author Jesse Wilson
031 * @since 1
032 */
033 @Beta
034 public abstract class AbstractExecutionThreadService implements Service {
035
036 /* use AbstractService for state management */
037 private final Service delegate = new AbstractService() {
038 @Override protected final void doStart() {
039 executor().execute(new Runnable() {
040 @Override
041 public void run() {
042 try {
043 startUp();
044 notifyStarted();
045
046 if (isRunning()) {
047 try {
048 AbstractExecutionThreadService.this.run();
049 } catch (Throwable t) {
050 try {
051 shutDown();
052 } catch (Exception ignored) {}
053 throw t;
054 }
055 }
056
057 shutDown();
058 notifyStopped();
059 } catch (Throwable t) {
060 notifyFailed(t);
061 throw Throwables.propagate(t);
062 }
063 }
064 });
065 }
066
067 @Override protected void doStop() {
068 triggerShutdown();
069 }
070 };
071
072 /**
073 * Start the service. This method is invoked on the execution thread.
074 */
075 protected void startUp() throws Exception {}
076
077 /**
078 * Run the service. This method is invoked on the execution thread.
079 * Implementations must respond to stop requests. You could poll for lifecycle
080 * changes in a work loop:
081 * <pre>
082 * public void run() {
083 * while ({@link #isRunning()}) {
084 * // perform a unit of work
085 * }
086 * }
087 * </pre>
088 * ...or you could respond to stop requests by implementing {@link
089 * #triggerShutdown()}, which should cause {@link #run()} to return.
090 */
091 protected abstract void run() throws Exception;
092
093 /**
094 * Stop the service. This method is invoked on the execution thread.
095 */
096 // TODO: consider supporting a TearDownTestCase-like API
097 protected void shutDown() throws Exception {}
098
099 /**
100 * Invoked to request the service to stop.
101 */
102 protected void triggerShutdown() {}
103
104 /**
105 * Returns the {@link Executor} that will be used to run this service.
106 * Subclasses may override this method to use a custom {@link Executor}, which
107 * may configure its worker thread with a specific name, thread group or
108 * priority. The returned executor's {@link Executor#execute(Runnable)
109 * execute()} method is called when this service is started, and should return
110 * promptly.
111 */
112 protected Executor executor() {
113 return new Executor() {
114 @Override
115 public void execute(Runnable command) {
116 new Thread(command, getServiceName()).start();
117 }
118 };
119 }
120
121 @Override public String toString() {
122 return getServiceName() + " [" + state() + "]";
123 }
124
125 // We override instead of using ForwardingService so that these can be final.
126
127 @Override public final ListenableFuture<State> start() {
128 return delegate.start();
129 }
130
131 @Override public final State startAndWait() {
132 return delegate.startAndWait();
133 }
134
135 @Override public final boolean isRunning() {
136 return delegate.isRunning();
137 }
138
139 @Override public final State state() {
140 return delegate.state();
141 }
142
143 @Override public final ListenableFuture<State> stop() {
144 return delegate.stop();
145 }
146
147 @Override public final State stopAndWait() {
148 return delegate.stopAndWait();
149 }
150
151 private String getServiceName() {
152 return getClass().getSimpleName();
153 }
154 }