AbstractExecutionThreadService.java revision 3c77433663281544363151bf284b0240dfd22a42
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" 59 + " after failure.", ignored); 60 } 61 throw t; 62 } 63 } 64 65 shutDown(); 66 notifyStopped(); 67 } catch (Throwable t) { 68 notifyFailed(t); 69 throw Throwables.propagate(t); 70 } 71 } 72 }); 73 } 74 75 @Override protected void doStop() { 76 triggerShutdown(); 77 } 78 }; 79 80 /** 81 * Constructor for use by subclasses. 82 */ 83 protected AbstractExecutionThreadService() {} 84 85 /** 86 * Start the service. This method is invoked on the execution thread. 87 * 88 * <p>By default this method does nothing. 89 */ 90 protected void startUp() throws Exception {} 91 92 /** 93 * Run the service. This method is invoked on the execution thread. 94 * Implementations must respond to stop requests. You could poll for lifecycle 95 * changes in a work loop: 96 * <pre> 97 * public void run() { 98 * while ({@link #isRunning()}) { 99 * // perform a unit of work 100 * } 101 * } 102 * </pre> 103 * ...or you could respond to stop requests by implementing {@link 104 * #triggerShutdown()}, which should cause {@link #run()} to return. 105 */ 106 protected abstract void run() throws Exception; 107 108 /** 109 * Stop the service. This method is invoked on the execution thread. 110 * 111 * <p>By default this method does nothing. 112 */ 113 // TODO: consider supporting a TearDownTestCase-like API 114 protected void shutDown() throws Exception {} 115 116 /** 117 * Invoked to request the service to stop. 118 * 119 * <p>By default this method does nothing. 120 */ 121 protected void triggerShutdown() {} 122 123 /** 124 * Returns the {@link Executor} that will be used to run this service. 125 * Subclasses may override this method to use a custom {@link Executor}, which 126 * may configure its worker thread with a specific name, thread group or 127 * priority. The returned executor's {@link Executor#execute(Runnable) 128 * execute()} method is called when this service is started, and should return 129 * promptly. 130 * 131 * <p>The default implementation returns a new {@link Executor} that sets the 132 * name of its threads to the string returned by {@link #serviceName} 133 */ 134 protected Executor executor() { 135 return new Executor() { 136 @Override 137 public void execute(Runnable command) { 138 MoreExecutors.newThread(serviceName(), command).start(); 139 } 140 }; 141 } 142 143 @Override public String toString() { 144 return serviceName() + " [" + state() + "]"; 145 } 146 147 // We override instead of using ForwardingService so that these can be final. 148 149 @Override public final ListenableFuture<State> start() { 150 return delegate.start(); 151 } 152 153 @Override public final State startAndWait() { 154 return delegate.startAndWait(); 155 } 156 157 @Override public final boolean isRunning() { 158 return delegate.isRunning(); 159 } 160 161 @Override public final State state() { 162 return delegate.state(); 163 } 164 165 @Override public final ListenableFuture<State> stop() { 166 return delegate.stop(); 167 } 168 169 @Override public final State stopAndWait() { 170 return delegate.stopAndWait(); 171 } 172 173 /** 174 * @since 13.0 175 */ 176 @Override public final void addListener(Listener listener, Executor executor) { 177 delegate.addListener(listener, executor); 178 } 179 180 /** 181 * @since 14.0 182 */ 183 @Override public final Throwable failureCause() { 184 return delegate.failureCause(); 185 } 186 187 /** 188 * Returns the name of this service. {@link AbstractExecutionThreadService} 189 * may include the name in debugging output. 190 * 191 * <p>Subclasses may override this method. 192 * 193 * @since 14.0 (present in 10.0 as getServiceName) 194 */ 195 protected String serviceName() { 196 return getClass().getSimpleName(); 197 } 198} 199