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 7package java.util.concurrent; 8import java.util.List; 9import java.util.Collection; 10import java.security.PrivilegedAction; 11import 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 */ 112public 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 * 123 * @throws SecurityException if a security manager exists and 124 * shutting down this ExecutorService may manipulate 125 * threads that the caller is not permitted to modify 126 * because it does not hold {@link 127 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>, 128 * or the security manager's <tt>checkAccess</tt> method 129 * denies access. 130 */ 131 void shutdown(); 132 133 /** 134 * Attempts to stop all actively executing tasks, halts the 135 * processing of waiting tasks, and returns a list of the tasks 136 * that were awaiting execution. 137 * 138 * <p>This method does not wait for actively executing tasks to 139 * terminate. Use {@link #awaitTermination awaitTermination} to 140 * do that. 141 * 142 * <p>There are no guarantees beyond best-effort attempts to stop 143 * processing actively executing tasks. For example, typical 144 * implementations will cancel via {@link Thread#interrupt}, so any 145 * task that fails to respond to interrupts may never terminate. 146 * 147 * @return list of tasks that never commenced execution 148 * @throws SecurityException if a security manager exists and 149 * shutting down this ExecutorService may manipulate 150 * threads that the caller is not permitted to modify 151 * because it does not hold {@link 152 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>, 153 * or the security manager's <tt>checkAccess</tt> method 154 * denies access. 155 */ 156 List<Runnable> shutdownNow(); 157 158 /** 159 * Returns <tt>true</tt> if this executor has been shut down. 160 * 161 * @return <tt>true</tt> if this executor has been shut down 162 */ 163 boolean isShutdown(); 164 165 /** 166 * Returns <tt>true</tt> if all tasks have completed following shut down. 167 * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless 168 * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first. 169 * 170 * @return <tt>true</tt> if all tasks have completed following shut down 171 */ 172 boolean isTerminated(); 173 174 /** 175 * Blocks until all tasks have completed execution after a shutdown 176 * request, or the timeout occurs, or the current thread is 177 * interrupted, whichever happens first. 178 * 179 * @param timeout the maximum time to wait 180 * @param unit the time unit of the timeout argument 181 * @return <tt>true</tt> if this executor terminated and 182 * <tt>false</tt> if the timeout elapsed before termination 183 * @throws InterruptedException if interrupted while waiting 184 */ 185 boolean awaitTermination(long timeout, TimeUnit unit) 186 throws InterruptedException; 187 188 189 /** 190 * Submits a value-returning task for execution and returns a 191 * Future representing the pending results of the task. The 192 * Future's <tt>get</tt> method will return the task's result upon 193 * successful completion. 194 * 195 * <p> 196 * If you would like to immediately block waiting 197 * for a task, you can use constructions of the form 198 * <tt>result = exec.submit(aCallable).get();</tt> 199 * 200 * <p> Note: The {@link Executors} class includes a set of methods 201 * that can convert some other common closure-like objects, 202 * for example, {@link java.security.PrivilegedAction} to 203 * {@link Callable} form so they can be submitted. 204 * 205 * @param task the task to submit 206 * @return a Future representing pending completion of the task 207 * @throws RejectedExecutionException if the task cannot be 208 * scheduled for execution 209 * @throws NullPointerException if the task is null 210 */ 211 <T> Future<T> submit(Callable<T> task); 212 213 /** 214 * Submits a Runnable task for execution and returns a Future 215 * representing that task. The Future's <tt>get</tt> method will 216 * return the given result upon successful completion. 217 * 218 * @param task the task to submit 219 * @param result the result to return 220 * @return a Future representing pending completion of the task 221 * @throws RejectedExecutionException if the task cannot be 222 * scheduled for execution 223 * @throws NullPointerException if the task is null 224 */ 225 <T> Future<T> submit(Runnable task, T result); 226 227 /** 228 * Submits a Runnable task for execution and returns a Future 229 * representing that task. The Future's <tt>get</tt> method will 230 * return <tt>null</tt> upon <em>successful</em> completion. 231 * 232 * @param task the task to submit 233 * @return a Future representing pending completion of the task 234 * @throws RejectedExecutionException if the task cannot be 235 * scheduled for execution 236 * @throws NullPointerException if the task is null 237 */ 238 Future<?> submit(Runnable task); 239 240 /** 241 * Executes the given tasks, returning a list of Futures holding 242 * their status and results when all complete. 243 * {@link Future#isDone} is <tt>true</tt> for each 244 * element of the returned list. 245 * Note that a <em>completed</em> task could have 246 * terminated either normally or by throwing an exception. 247 * The results of this method are undefined if the given 248 * collection is modified while this operation is in progress. 249 * 250 * @param tasks the collection of tasks 251 * @return A list of Futures representing the tasks, in the same 252 * sequential order as produced by the iterator for the 253 * given task list, each of which has completed. 254 * @throws InterruptedException if interrupted while waiting, in 255 * which case unfinished tasks are cancelled. 256 * @throws NullPointerException if tasks or any of its elements are <tt>null</tt> 257 * @throws RejectedExecutionException if any task cannot be 258 * scheduled for execution 259 */ 260 261 <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks) 262 throws InterruptedException; 263 264 /** 265 * Executes the given tasks, returning a list of Futures holding 266 * their status and results 267 * when all complete or the timeout expires, whichever happens first. 268 * {@link Future#isDone} is <tt>true</tt> for each 269 * element of the returned list. 270 * Upon return, tasks that have not completed are cancelled. 271 * Note that a <em>completed</em> task could have 272 * terminated either normally or by throwing an exception. 273 * The results of this method are undefined if the given 274 * collection is modified while this operation is in progress. 275 * 276 * @param tasks the collection of tasks 277 * @param timeout the maximum time to wait 278 * @param unit the time unit of the timeout argument 279 * @return a list of Futures representing the tasks, in the same 280 * sequential order as produced by the iterator for the 281 * given task list. If the operation did not time out, 282 * each task will have completed. If it did time out, some 283 * of these tasks will not have completed. 284 * @throws InterruptedException if interrupted while waiting, in 285 * which case unfinished tasks are cancelled 286 * @throws NullPointerException if tasks, any of its elements, or 287 * unit are <tt>null</tt> 288 * @throws RejectedExecutionException if any task cannot be scheduled 289 * for execution 290 */ 291 <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, 292 long timeout, TimeUnit unit) 293 throws InterruptedException; 294 295 /** 296 * Executes the given tasks, returning the result 297 * of one that has completed successfully (i.e., without throwing 298 * an exception), if any do. Upon normal or exceptional return, 299 * tasks that have not completed are cancelled. 300 * The results of this method are undefined if the given 301 * collection is modified while this operation is in progress. 302 * 303 * @param tasks the collection of tasks 304 * @return the result returned by one of the tasks 305 * @throws InterruptedException if interrupted while waiting 306 * @throws NullPointerException if tasks or any of its elements 307 * are <tt>null</tt> 308 * @throws IllegalArgumentException if tasks is empty 309 * @throws ExecutionException if no task successfully completes 310 * @throws RejectedExecutionException if tasks cannot be scheduled 311 * for execution 312 */ 313 <T> T invokeAny(Collection<Callable<T>> tasks) 314 throws InterruptedException, ExecutionException; 315 316 /** 317 * Executes the given tasks, returning the result 318 * of one that has completed successfully (i.e., without throwing 319 * an exception), if any do before the given timeout elapses. 320 * Upon normal or exceptional return, tasks that have not 321 * completed are cancelled. 322 * The results of this method are undefined if the given 323 * collection is modified while this operation is in progress. 324 * 325 * @param tasks the collection of tasks 326 * @param timeout the maximum time to wait 327 * @param unit the time unit of the timeout argument 328 * @return the result returned by one of the tasks. 329 * @throws InterruptedException if interrupted while waiting 330 * @throws NullPointerException if tasks, any of its elements, or 331 * unit are <tt>null</tt> 332 * @throws TimeoutException if the given timeout elapses before 333 * any task successfully completes 334 * @throws ExecutionException if no task successfully completes 335 * @throws RejectedExecutionException if tasks cannot be scheduled 336 * for execution 337 */ 338 <T> T invokeAny(Collection<Callable<T>> tasks, 339 long timeout, TimeUnit unit) 340 throws InterruptedException, ExecutionException, TimeoutException; 341} 342