001/** 002The contents of this file are subject to the Mozilla Public License Version 1.1 003(the "License"); you may not use this file except in compliance with the License. 004You may obtain a copy of the License at http://www.mozilla.org/MPL/ 005Software distributed under the License is distributed on an "AS IS" basis, 006WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 007specific language governing rights and limitations under the License. 008 009The Original Code is "ManagedRunnable.java". Description: 010"Base class for a unified management of threads with a defined lifecycle." 011 012The Initial Developer of the Original Code is University Health Network. Copyright (C) 0132001. All Rights Reserved. 014 015Contributor(s): ______________________________________. 016 017Alternatively, the contents of this file may be used under the terms of the 018GNU General Public License (the "GPL"), in which case the provisions of the GPL are 019applicable instead of those above. If you wish to allow use of your version of this 020file only under the terms of the GPL and not to allow others to use your version 021of this file under the MPL, indicate your decision by deleting the provisions above 022and replace them with the notice and other provisions required by the GPL License. 023If you do not delete the provisions above, a recipient may use your version of 024this file under either the MPL or the GPL. 025 */ 026package ca.uhn.hl7v2.concurrent; 027 028import java.util.concurrent.CountDownLatch; 029import java.util.concurrent.ExecutionException; 030import java.util.concurrent.ExecutorService; 031import java.util.concurrent.Future; 032import java.util.concurrent.TimeUnit; 033import java.util.concurrent.TimeoutException; 034 035import org.slf4j.Logger; 036import org.slf4j.LoggerFactory; 037 038/** 039 * Base class for a unified management of threads with a defined lifecycle. It 040 * uses a {@link #keepRunning} flag to regularly terminate a thread. Classes 041 * implementing this class must implement {@link #handle()} to do the main 042 * processing. {@link #afterStartup()} and {@link #afterTermination()} can be 043 * overridden to acquire and release resources required for processing. 044 */ 045public abstract class Service implements Runnable { 046 047 private static final Logger log = LoggerFactory 048 .getLogger(Service.class); 049 private volatile boolean keepRunning; 050 private long shutdownTimeout = 3000L; 051 private final String name; 052 private final ExecutorService executorService; 053 private Future<?> thread; 054 private Throwable serviceExitedWithException; 055 private final CountDownLatch startupLatch = new CountDownLatch(1); 056 057 public Service(String name, ExecutorService executorService) { 058 super(); 059 this.name = name; 060 this.executorService = executorService; 061 } 062 063 /** 064 * @return Returns <code>true</code> if the server has been started, and has 065 * not yet been stopped. 066 */ 067 public boolean isRunning() { 068 return keepRunning; 069 } 070 071 public ExecutorService getExecutorService() { 072 return executorService; 073 } 074 075 /** 076 * Sets the time in milliseconds how long {@link #stopAndWait()} should wait 077 * for the thread to terminate. Defaults to 3000ms. 078 * 079 * @param shutdownTimeout timout in milliseconds 080 */ 081 public void setShutdownTimeout(long shutdownTimeout) { 082 this.shutdownTimeout = shutdownTimeout; 083 } 084 085 /** 086 * Starts the server listening for connections in a new thread. This 087 * continues until <code>stop()</code> is called. 088 * 089 * @throws IllegalStateException If the service is already running (i.e. 090 * start() has already been called. 091 * 092 */ 093 public void start() { 094 if (keepRunning) { 095 throw new IllegalStateException("Service is already running"); 096 } 097 log.debug("Starting service {}", name); 098 keepRunning = true; 099 ExecutorService service = getExecutorService(); 100 if (service.isShutdown()) { 101 throw new IllegalStateException("ExecutorService is shut down"); 102 } 103 thread = service.submit(this); 104 } 105 106 /** 107 * <p> 108 * Starts the server listening for connections in a new thread. This 109 * continues until <code>stop()</code> is called. 110 * </p> 111 * <p> 112 * Unlike {@link #start()}, this method will not return until the processing 113 * loop has completed at least once. This does not imply any kind of successful 114 * processing, but should at least provide a guarantee that the service 115 * has finished initializing itself. 116 * </p> 117 */ 118 public void startAndWait() throws InterruptedException { 119 start(); 120 startupLatch.await(); 121 } 122 123 /** 124 * Prepare any resources before entering the main thread. 125 * 126 * @throws RuntimeException 127 * if resources could not acquired. In this case, the thread 128 * will shutdown. Note that {@link #afterTermination()} is 129 * called before. 130 */ 131 protected void afterStartup() { 132 } 133 134 /** 135 * The main task of the thread, called in a loop as long as 136 * {@link #isRunning()} returns true. Overridden methods are responsible for 137 * yielding or pausing the thread when it's idle. The method must also not 138 * block indefinitely so that a call to {@link #stop()} is able to 139 * gracefully terminate the thread. 140 */ 141 protected abstract void handle(); 142 143 /** 144 * Advises the thread to leave its main loop. {@link #prepareTermination()} is 145 * called before this method returns. {@link #afterTermination()} is 146 * called after the thread has left its main loop. 147 */ 148 public void stop() { 149 if (isRunning()) { 150 prepareTermination(); 151 } 152 } 153 154 public void waitForTermination() { 155 if (!thread.isDone()) 156 try { 157 thread.get(shutdownTimeout, TimeUnit.MILLISECONDS); 158 } catch (ExecutionException | InterruptedException ee) { 159 // empty 160 } catch (TimeoutException te) { 161 log.warn( 162 "Thread did not stop after {} milliseconds. Now cancelling.", 163 shutdownTimeout); 164 thread.cancel(true); 165 } 166 } 167 168 /** 169 * Stops the thread by leaving its main loop. {@link #afterTermination()} is 170 * called before the thread is terminated. The method waits until the thread 171 * has stopped. 172 */ 173 public final void stopAndWait() { 174 stop(); 175 waitForTermination(); 176 } 177 178 /** 179 * Clean up any resources initialized in {@link #afterStartup()}. 180 */ 181 protected void afterTermination() { 182 } 183 184 /** 185 * Prepare thread to leave its main loop. By default sets {@link #keepRunning} 186 * to false, but some implementations may need to do additional stuff. 187 */ 188 protected void prepareTermination() { 189 log.debug("Prepare to stop thread {}", name); 190 keepRunning = false; 191 } 192 193 /** 194 * Runs the thread. 195 * 196 * @see java.lang.Runnable#run() 197 */ 198 public final void run() { 199 try { 200 afterStartup(); 201 log.debug("Thread {} entering main loop", name); 202 while (isRunning()) { 203 handle(); 204 startupLatch.countDown(); 205 } 206 log.debug("Thread {} leaving main loop", name); 207 } catch (RuntimeException t) { 208 if (t.getCause() != null) { 209 serviceExitedWithException = t.getCause(); 210 } else { 211 serviceExitedWithException = t; 212 } 213 log.warn("Thread exiting main loop due to exception:", t); 214 } catch (Throwable t) { 215 serviceExitedWithException = t; 216 log.warn("Thread exiting main loop due to exception:", t); 217 } finally { 218 startupLatch.countDown(); 219 afterTermination(); 220 } 221 222 } 223 224 /** 225 * Provide the exception which caused this service to fail 226 */ 227 protected void setServiceExitedWithException(Throwable theThreadExitedWithException) { 228 serviceExitedWithException = theThreadExitedWithException; 229 } 230 231 232 /** 233 * If this service exited with an exception, ths method returns that exception. This is useful for 234 * detecting if the service failed unexpectedly 235 */ 236 public Throwable getServiceExitedWithException() { 237 return serviceExitedWithException; 238 } 239 240}