1 /* 2 * Written by Doug Lea with assistance from members of JCP JSR-166 3 * Expert Group and released to the public domain, as explained at 4 * http://creativecommons.org/licenses/publicdomain 5 */ 6 7 package java.util.concurrent; 8 import java.util.List; 9 import java.util.Collection; 10 import java.security.PrivilegedAction; 11 import java.security.PrivilegedExceptionAction; 12 13 /** 14 * An {@link Executor} that provides methods to manage termination and 15 * methods that can produce a {@link Future} for tracking progress of 16 * one or more asynchronous tasks. 17 * 18 * <p> An <tt>ExecutorService</tt> can be shut down, which will cause 19 * it to reject new tasks. Two different methods are provided for 20 * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown} 21 * method will allow previously submitted tasks to execute before 22 * terminating, while the {@link #shutdownNow} method prevents waiting 23 * tasks from starting and attempts to stop currently executing tasks. 24 * Upon termination, an executor has no tasks actively executing, no 25 * tasks awaiting execution, and no new tasks can be submitted. An 26 * unused <tt>ExecutorService</tt> should be shut down to allow 27 * reclamation of its resources. 28 * 29 * <p> Method <tt>submit</tt> extends base method {@link 30 * Executor#execute} by creating and returning a {@link Future} that 31 * can be used to cancel execution and/or wait for completion. 32 * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most 33 * commonly useful forms of bulk execution, executing a collection of 34 * tasks and then waiting for at least one, or all, to 35 * complete. (Class {@link ExecutorCompletionService} can be used to 36 * write customized variants of these methods.) 37 * 38 * <p>The {@link Executors} class provides factory methods for the 39 * executor services provided in this package. 40 * 41 * <h3>Usage Examples</h3> 42 * 43 * Here is a sketch of a network service in which threads in a thread 44 * pool service incoming requests. It uses the preconfigured {@link 45 * Executors#newFixedThreadPool} factory method: 46 * 47 * <pre> 48 * class NetworkService implements Runnable { 49 * private final ServerSocket serverSocket; 50 * private final ExecutorService pool; 51 * 52 * public NetworkService(int port, int poolSize) 53 * throws IOException { 54 * serverSocket = new ServerSocket(port); 55 * pool = Executors.newFixedThreadPool(poolSize); 56 * } 57 * 58 * public void run() { // run the service 59 * try { 60 * for (;;) { 61 * pool.execute(new Handler(serverSocket.accept())); 62 * } 63 * } catch (IOException ex) { 64 * pool.shutdown(); 65 * } 66 * } 67 * } 68 * 69 * class Handler implements Runnable { 70 * private final Socket socket; 71 * Handler(Socket socket) { this.socket = socket; } 72 * public void run() { 73 * // read and service request on socket 74 * } 75 * } 76 * </pre> 77 * 78 * The following method shuts down an <tt>ExecutorService</tt> in two phases, 79 * first by calling <tt>shutdown</tt> to reject incoming tasks, and then 80 * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks: 81 * 82 * <pre> 83 * void shutdownAndAwaitTermination(ExecutorService pool) { 84 * pool.shutdown(); // Disable new tasks from being submitted 85 * try { 86 * // Wait a while for existing tasks to terminate 87 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { 88 * pool.shutdownNow(); // Cancel currently executing tasks 89 * // Wait a while for tasks to respond to being cancelled 90 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) 91 * System.err.println("Pool did not terminate"); 92 * } 93 * } catch (InterruptedException ie) { 94 * // (Re-)Cancel if current thread also interrupted 95 * pool.shutdownNow(); 96 * // Preserve interrupt status 97 * Thread.currentThread().interrupt(); 98 * } 99 * } 100 * </pre> 101 * 102 * <p>Memory consistency effects: Actions in a thread prior to the 103 * submission of a {@code Runnable} or {@code Callable} task to an 104 * {@code ExecutorService} 105 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> 106 * any actions taken by that task, which in turn <i>happen-before</i> the 107 * result is retrieved via {@code Future.get()}. 108 * 109 * @since 1.5 110 * @author Doug Lea 111 */ 112 public interface ExecutorService extends Executor { 113 114 /** 115 * Initiates an orderly shutdown in which previously submitted 116 * tasks are executed, but no new tasks will be accepted. 117 * Invocation has no additional effect if already shut down. 118 * 119 * <p>This method does not wait for previously submitted tasks to 120 * complete execution. Use {@link #awaitTermination awaitTermination} 121 * to do that. 122 */ shutdown()123 void shutdown(); 124 125 /** 126 * Attempts to stop all actively executing tasks, halts the 127 * processing of waiting tasks, and returns a list of the tasks 128 * that were awaiting execution. 129 * 130 * <p>This method does not wait for actively executing tasks to 131 * terminate. Use {@link #awaitTermination awaitTermination} to 132 * do that. 133 * 134 * <p>There are no guarantees beyond best-effort attempts to stop 135 * processing actively executing tasks. For example, typical 136 * implementations will cancel via {@link Thread#interrupt}, so any 137 * task that fails to respond to interrupts may never terminate. 138 * 139 * @return list of tasks that never commenced execution 140 */ shutdownNow()141 List<Runnable> shutdownNow(); 142 143 /** 144 * Returns <tt>true</tt> if this executor has been shut down. 145 * 146 * @return <tt>true</tt> if this executor has been shut down 147 */ isShutdown()148 boolean isShutdown(); 149 150 /** 151 * Returns <tt>true</tt> if all tasks have completed following shut down. 152 * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless 153 * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first. 154 * 155 * @return <tt>true</tt> if all tasks have completed following shut down 156 */ isTerminated()157 boolean isTerminated(); 158 159 /** 160 * Blocks until all tasks have completed execution after a shutdown 161 * request, or the timeout occurs, or the current thread is 162 * interrupted, whichever happens first. 163 * 164 * @param timeout the maximum time to wait 165 * @param unit the time unit of the timeout argument 166 * @return <tt>true</tt> if this executor terminated and 167 * <tt>false</tt> if the timeout elapsed before termination 168 * @throws InterruptedException if interrupted while waiting 169 */ awaitTermination(long timeout, TimeUnit unit)170 boolean awaitTermination(long timeout, TimeUnit unit) 171 throws InterruptedException; 172 173 174 /** 175 * Submits a value-returning task for execution and returns a 176 * Future representing the pending results of the task. The 177 * Future's <tt>get</tt> method will return the task's result upon 178 * successful completion. 179 * 180 * <p> 181 * If you would like to immediately block waiting 182 * for a task, you can use constructions of the form 183 * <tt>result = exec.submit(aCallable).get();</tt> 184 * 185 * <p> Note: The {@link Executors} class includes a set of methods 186 * that can convert some other common closure-like objects, 187 * for example, {@link java.security.PrivilegedAction} to 188 * {@link Callable} form so they can be submitted. 189 * 190 * @param task the task to submit 191 * @return a Future representing pending completion of the task 192 * @throws RejectedExecutionException if the task cannot be 193 * scheduled for execution 194 * @throws NullPointerException if the task is null 195 */ submit(Callable<T> task)196 <T> Future<T> submit(Callable<T> task); 197 198 /** 199 * Submits a Runnable task for execution and returns a Future 200 * representing that task. The Future's <tt>get</tt> method will 201 * return the given result upon successful completion. 202 * 203 * @param task the task to submit 204 * @param result the result to return 205 * @return a Future representing pending completion of the task 206 * @throws RejectedExecutionException if the task cannot be 207 * scheduled for execution 208 * @throws NullPointerException if the task is null 209 */ submit(Runnable task, T result)210 <T> Future<T> submit(Runnable task, T result); 211 212 /** 213 * Submits a Runnable task for execution and returns a Future 214 * representing that task. The Future's <tt>get</tt> method will 215 * return <tt>null</tt> upon <em>successful</em> completion. 216 * 217 * @param task the task to submit 218 * @return a Future representing pending completion of the task 219 * @throws RejectedExecutionException if the task cannot be 220 * scheduled for execution 221 * @throws NullPointerException if the task is null 222 */ submit(Runnable task)223 Future<?> submit(Runnable task); 224 225 /** 226 * Executes the given tasks, returning a list of Futures holding 227 * their status and results when all complete. 228 * {@link Future#isDone} is <tt>true</tt> for each 229 * element of the returned list. 230 * Note that a <em>completed</em> task could have 231 * terminated either normally or by throwing an exception. 232 * The results of this method are undefined if the given 233 * collection is modified while this operation is in progress. 234 * 235 * @param tasks the collection of tasks 236 * @return A list of Futures representing the tasks, in the same 237 * sequential order as produced by the iterator for the 238 * given task list, each of which has completed. 239 * @throws InterruptedException if interrupted while waiting, in 240 * which case unfinished tasks are cancelled. 241 * @throws NullPointerException if tasks or any of its elements are <tt>null</tt> 242 * @throws RejectedExecutionException if any task cannot be 243 * scheduled for execution 244 */ 245 invokeAll(Collection<? extends Callable<T>> tasks)246 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) 247 throws InterruptedException; 248 249 /** 250 * Executes the given tasks, returning a list of Futures holding 251 * their status and results 252 * when all complete or the timeout expires, whichever happens first. 253 * {@link Future#isDone} is <tt>true</tt> for each 254 * element of the returned list. 255 * Upon return, tasks that have not completed are cancelled. 256 * Note that a <em>completed</em> task could have 257 * terminated either normally or by throwing an exception. 258 * The results of this method are undefined if the given 259 * collection is modified while this operation is in progress. 260 * 261 * @param tasks the collection of tasks 262 * @param timeout the maximum time to wait 263 * @param unit the time unit of the timeout argument 264 * @return a list of Futures representing the tasks, in the same 265 * sequential order as produced by the iterator for the 266 * given task list. If the operation did not time out, 267 * each task will have completed. If it did time out, some 268 * of these tasks will not have completed. 269 * @throws InterruptedException if interrupted while waiting, in 270 * which case unfinished tasks are cancelled 271 * @throws NullPointerException if tasks, any of its elements, or 272 * unit are <tt>null</tt> 273 * @throws RejectedExecutionException if any task cannot be scheduled 274 * for execution 275 */ invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)276 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, 277 long timeout, TimeUnit unit) 278 throws InterruptedException; 279 280 /** 281 * Executes the given tasks, returning the result 282 * of one that has completed successfully (i.e., without throwing 283 * an exception), if any do. Upon normal or exceptional return, 284 * tasks that have not completed are cancelled. 285 * The results of this method are undefined if the given 286 * collection is modified while this operation is in progress. 287 * 288 * @param tasks the collection of tasks 289 * @return the result returned by one of the tasks 290 * @throws InterruptedException if interrupted while waiting 291 * @throws NullPointerException if tasks or any element task 292 * subject to execution is <tt>null</tt> 293 * @throws IllegalArgumentException if tasks is empty 294 * @throws ExecutionException if no task successfully completes 295 * @throws RejectedExecutionException if tasks cannot be scheduled 296 * for execution 297 */ invokeAny(Collection<? extends Callable<T>> tasks)298 <T> T invokeAny(Collection<? extends Callable<T>> tasks) 299 throws InterruptedException, ExecutionException; 300 301 /** 302 * Executes the given tasks, returning the result 303 * of one that has completed successfully (i.e., without throwing 304 * an exception), if any do before the given timeout elapses. 305 * Upon normal or exceptional return, tasks that have not 306 * completed are cancelled. 307 * The results of this method are undefined if the given 308 * collection is modified while this operation is in progress. 309 * 310 * @param tasks the collection of tasks 311 * @param timeout the maximum time to wait 312 * @param unit the time unit of the timeout argument 313 * @return the result returned by one of the tasks. 314 * @throws InterruptedException if interrupted while waiting 315 * @throws NullPointerException if tasks, or unit, or any element 316 * task subject to execution is <tt>null</tt> 317 * @throws TimeoutException if the given timeout elapses before 318 * any task successfully completes 319 * @throws ExecutionException if no task successfully completes 320 * @throws RejectedExecutionException if tasks cannot be scheduled 321 * for execution 322 */ invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)323 <T> T invokeAny(Collection<? extends Callable<T>> tasks, 324 long timeout, TimeUnit unit) 325 throws InterruptedException, ExecutionException, TimeoutException; 326 } 327