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