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