1/*2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3 *4 * This code is free software; you can redistribute it and/or modify it5 * under the terms of the GNU General Public License version 2 only, as6 * published by the Free Software Foundation. Oracle designates this7 * particular file as subject to the "Classpath" exception as provided8 * by Oracle in the LICENSE file that accompanied this code.9 *10 * This code is distributed in the hope that it will be useful, but WITHOUT11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13 * version 2 for more details (a copy is included in the LICENSE file that14 * accompanied this code).15 *16 * You should have received a copy of the GNU General Public License version17 * 2 along with this work; if not, write to the Free Software Foundation,18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19 *20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21 * or visit www.oracle.com if you need additional information or have any22 * questions.23 */2425/*26 * This file is available under and governed by the GNU General Public27 * License version 2 only, as published by the Free Software Foundation.28 * However, the following notice accompanied the original version of this29 * file:30 *31 * Written by Doug Lea with assistance from members of JCP JSR-16632 * Expert Group and released to the public domain, as explained at33 * http://creativecommons.org/publicdomain/zero/1.0/34 */3536package java.util.concurrent;
37import java.util.List;
38import java.util.Collection;
3940/**41 * An {@link Executor} that provides methods to manage termination and42 * methods that can produce a {@link Future} for tracking progress of43 * one or more asynchronous tasks.44 *45 * <p>An {@code ExecutorService} can be shut down, which will cause46 * it to reject new tasks. Two different methods are provided for47 * shutting down an {@code ExecutorService}. The {@link #shutdown}48 * method will allow previously submitted tasks to execute before49 * terminating, while the {@link #shutdownNow} method prevents waiting50 * tasks from starting and attempts to stop currently executing tasks.51 * Upon termination, an executor has no tasks actively executing, no52 * tasks awaiting execution, and no new tasks can be submitted. An53 * unused {@code ExecutorService} should be shut down to allow54 * reclamation of its resources.55 *56 * <p>Method {@code submit} extends base method {@link57 * Executor#execute(Runnable)} by creating and returning a {@link Future}58 * that can be used to cancel execution and/or wait for completion.59 * Methods {@code invokeAny} and {@code invokeAll} perform the most60 * commonly useful forms of bulk execution, executing a collection of61 * tasks and then waiting for at least one, or all, to62 * complete. (Class {@link ExecutorCompletionService} can be used to63 * write customized variants of these methods.)64 *65 * <p>The {@link Executors} class provides factory methods for the66 * executor services provided in this package.67 *68 * <h3>Usage Examples</h3>69 *70 * Here is a sketch of a network service in which threads in a thread71 * pool service incoming requests. It uses the preconfigured {@link72 * Executors#newFixedThreadPool} factory method:73 *74 * <pre> {@code75 * class NetworkService implements Runnable {76 * private final ServerSocket serverSocket;77 * private final ExecutorService pool;78 *79 * public NetworkService(int port, int poolSize)80 * throws IOException {81 * serverSocket = new ServerSocket(port);82 * pool = Executors.newFixedThreadPool(poolSize);83 * }84 *85 * public void run() { // run the service86 * try {87 * for (;;) {88 * pool.execute(new Handler(serverSocket.accept()));89 * }90 * } catch (IOException ex) {91 * pool.shutdown();92 * }93 * }94 * }95 *96 * class Handler implements Runnable {97 * private final Socket socket;98 * Handler(Socket socket) { this.socket = socket; }99 * public void run() {100 * // read and service request on socket101 * }102 * }}</pre>103 *104 * The following method shuts down an {@code ExecutorService} in two phases,105 * first by calling {@code shutdown} to reject incoming tasks, and then106 * calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:107 *108 * <pre> {@code109 * void shutdownAndAwaitTermination(ExecutorService pool) {110 * pool.shutdown(); // Disable new tasks from being submitted111 * try {112 * // Wait a while for existing tasks to terminate113 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {114 * pool.shutdownNow(); // Cancel currently executing tasks115 * // Wait a while for tasks to respond to being cancelled116 * if (!pool.awaitTermination(60, TimeUnit.SECONDS))117 * System.err.println("Pool did not terminate");118 * }119 * } catch (InterruptedException ie) {120 * // (Re-)Cancel if current thread also interrupted121 * pool.shutdownNow();122 * // Preserve interrupt status123 * Thread.currentThread().interrupt();124 * }125 * }}</pre>126 *127 * <p>Memory consistency effects: Actions in a thread prior to the128 * submission of a {@code Runnable} or {@code Callable} task to an129 * {@code ExecutorService}130 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>131 * any actions taken by that task, which in turn <i>happen-before</i> the132 * result is retrieved via {@code Future.get()}.133 *134 * @since 1.5135 * @author Doug Lea136 */137publicinterfaceExecutorServiceextendsExecutor {
138139/**140 * Initiates an orderly shutdown in which previously submitted141 * tasks are executed, but no new tasks will be accepted.142 * Invocation has no additional effect if already shut down.143 *144 * <p>This method does not wait for previously submitted tasks to145 * complete execution. Use {@link #awaitTermination awaitTermination}146 * to do that.147 *148 * @throws SecurityException if a security manager exists and149 * shutting down this ExecutorService may manipulate150 * threads that the caller is not permitted to modify151 * because it does not hold {@link152 * java.lang.RuntimePermission}{@code ("modifyThread")},153 * or the security manager's {@code checkAccess} method154 * denies access.155 */156void shutdown();
157158/**159 * Attempts to stop all actively executing tasks, halts the160 * processing of waiting tasks, and returns a list of the tasks161 * that were awaiting execution.162 *163 * <p>This method does not wait for actively executing tasks to164 * terminate. Use {@link #awaitTermination awaitTermination} to165 * do that.166 *167 * <p>There are no guarantees beyond best-effort attempts to stop168 * processing actively executing tasks. For example, typical169 * implementations will cancel via {@link Thread#interrupt}, so any170 * task that fails to respond to interrupts may never terminate.171 *172 * @return list of tasks that never commenced execution173 * @throws SecurityException if a security manager exists and174 * shutting down this ExecutorService may manipulate175 * threads that the caller is not permitted to modify176 * because it does not hold {@link177 * java.lang.RuntimePermission}{@code ("modifyThread")},178 * or the security manager's {@code checkAccess} method179 * denies access.180 */181 List<Runnable> shutdownNow();
182183/**184 * Returns {@code true} if this executor has been shut down.185 *186 * @return {@code true} if this executor has been shut down187 */188boolean isShutdown();
189190/**191 * Returns {@code true} if all tasks have completed following shut down.192 * Note that {@code isTerminated} is never {@code true} unless193 * either {@code shutdown} or {@code shutdownNow} was called first.194 *195 * @return {@code true} if all tasks have completed following shut down196 */197boolean isTerminated();
198199/**200 * Blocks until all tasks have completed execution after a shutdown201 * request, or the timeout occurs, or the current thread is202 * interrupted, whichever happens first.203 *204 * @param timeout the maximum time to wait205 * @param unit the time unit of the timeout argument206 * @return {@code true} if this executor terminated and207 * {@code false} if the timeout elapsed before termination208 * @throws InterruptedException if interrupted while waiting209 */210boolean awaitTermination(long timeout, TimeUnit unit)
211throws InterruptedException;
212213/**214 * Submits a value-returning task for execution and returns a215 * Future representing the pending results of the task. The216 * Future's {@code get} method will return the task's result upon217 * successful completion.218 *219 * <p>220 * If you would like to immediately block waiting221 * for a task, you can use constructions of the form222 * {@code result = exec.submit(aCallable).get();}223 *224 * <p>Note: The {@link Executors} class includes a set of methods225 * that can convert some other common closure-like objects,226 * for example, {@link java.security.PrivilegedAction} to227 * {@link Callable} form so they can be submitted.228 *229 * @param task the task to submit230 * @param <T> the type of the task's result231 * @return a Future representing pending completion of the task232 * @throws RejectedExecutionException if the task cannot be233 * scheduled for execution234 * @throws NullPointerException if the task is null235 */236 <T> Future<T> submit(Callable<T> task);
237238/**239 * Submits a Runnable task for execution and returns a Future240 * representing that task. The Future's {@code get} method will241 * return the given result upon successful completion.242 *243 * @param task the task to submit244 * @param result the result to return245 * @param <T> the type of the result246 * @return a Future representing pending completion of the task247 * @throws RejectedExecutionException if the task cannot be248 * scheduled for execution249 * @throws NullPointerException if the task is null250 */251 <T> Future<T> submit(Runnable task, T result);
252253/**254 * Submits a Runnable task for execution and returns a Future255 * representing that task. The Future's {@code get} method will256 * return {@code null} upon <em>successful</em> completion.257 *258 * @param task the task to submit259 * @return a Future representing pending completion of the task260 * @throws RejectedExecutionException if the task cannot be261 * scheduled for execution262 * @throws NullPointerException if the task is null263 */264 Future<?> submit(Runnable task);
265266/**267 * Executes the given tasks, returning a list of Futures holding268 * their status and results when all complete.269 * {@link Future#isDone} is {@code true} for each270 * element of the returned list.271 * Note that a <em>completed</em> task could have272 * terminated either normally or by throwing an exception.273 * The results of this method are undefined if the given274 * collection is modified while this operation is in progress.275 *276 * @param tasks the collection of tasks277 * @param <T> the type of the values returned from the tasks278 * @return a list of Futures representing the tasks, in the same279 * sequential order as produced by the iterator for the280 * given task list, each of which has completed281 * @throws InterruptedException if interrupted while waiting, in282 * which case unfinished tasks are cancelled283 * @throws NullPointerException if tasks or any of its elements are {@code null}284 * @throws RejectedExecutionException if any task cannot be285 * scheduled for execution286 */287 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
288throws InterruptedException;
289290/**291 * Executes the given tasks, returning a list of Futures holding292 * their status and results293 * when all complete or the timeout expires, whichever happens first.294 * {@link Future#isDone} is {@code true} for each295 * element of the returned list.296 * Upon return, tasks that have not completed are cancelled.297 * Note that a <em>completed</em> task could have298 * terminated either normally or by throwing an exception.299 * The results of this method are undefined if the given300 * collection is modified while this operation is in progress.301 *302 * @param tasks the collection of tasks303 * @param timeout the maximum time to wait304 * @param unit the time unit of the timeout argument305 * @param <T> the type of the values returned from the tasks306 * @return a list of Futures representing the tasks, in the same307 * sequential order as produced by the iterator for the308 * given task list. If the operation did not time out,309 * each task will have completed. If it did time out, some310 * of these tasks will not have completed.311 * @throws InterruptedException if interrupted while waiting, in312 * which case unfinished tasks are cancelled313 * @throws NullPointerException if tasks, any of its elements, or314 * unit are {@code null}315 * @throws RejectedExecutionException if any task cannot be scheduled316 * for execution317 */318 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
319long timeout, TimeUnit unit)
320throws InterruptedException;
321322/**323 * Executes the given tasks, returning the result324 * of one that has completed successfully (i.e., without throwing325 * an exception), if any do. Upon normal or exceptional return,326 * tasks that have not completed are cancelled.327 * The results of this method are undefined if the given328 * collection is modified while this operation is in progress.329 *330 * @param tasks the collection of tasks331 * @param <T> the type of the values returned from the tasks332 * @return the result returned by one of the tasks333 * @throws InterruptedException if interrupted while waiting334 * @throws NullPointerException if tasks or any element task335 * subject to execution is {@code null}336 * @throws IllegalArgumentException if tasks is empty337 * @throws ExecutionException if no task successfully completes338 * @throws RejectedExecutionException if tasks cannot be scheduled339 * for execution340 */341 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
342throws InterruptedException, ExecutionException;
343344/**345 * Executes the given tasks, returning the result346 * of one that has completed successfully (i.e., without throwing347 * an exception), if any do before the given timeout elapses.348 * Upon normal or exceptional return, tasks that have not349 * completed are cancelled.350 * The results of this method are undefined if the given351 * collection is modified while this operation is in progress.352 *353 * @param tasks the collection of tasks354 * @param timeout the maximum time to wait355 * @param unit the time unit of the timeout argument356 * @param <T> the type of the values returned from the tasks357 * @return the result returned by one of the tasks358 * @throws InterruptedException if interrupted while waiting359 * @throws NullPointerException if tasks, or unit, or any element360 * task subject to execution is {@code null}361 * @throws TimeoutException if the given timeout elapses before362 * any task successfully completes363 * @throws ExecutionException if no task successfully completes364 * @throws RejectedExecutionException if tasks cannot be scheduled365 * for execution366 */367 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
368long timeout, TimeUnit unit)
369throws InterruptedException, ExecutionException, TimeoutException;
370 }