2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 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.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
37 import java.util.List;
38 import java.util.Collection;
39 import java.security.PrivilegedAction;
40 import java.security.PrivilegedExceptionAction;
43 * An {@link Executor} that provides methods to manage termination and
44 * methods that can produce a {@link Future} for tracking progress of
45 * one or more asynchronous tasks.
47 * <p> An <tt>ExecutorService</tt> can be shut down, which will cause
48 * it to reject new tasks. Two different methods are provided for
49 * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown}
50 * method will allow previously submitted tasks to execute before
51 * terminating, while the {@link #shutdownNow} method prevents waiting
52 * tasks from starting and attempts to stop currently executing tasks.
53 * Upon termination, an executor has no tasks actively executing, no
54 * tasks awaiting execution, and no new tasks can be submitted. An
55 * unused <tt>ExecutorService</tt> should be shut down to allow
56 * reclamation of its resources.
58 * <p> Method <tt>submit</tt> extends base method {@link
59 * Executor#execute} by creating and returning a {@link Future} that
60 * can be used to cancel execution and/or wait for completion.
61 * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
62 * commonly useful forms of bulk execution, executing a collection of
63 * tasks and then waiting for at least one, or all, to
64 * complete. (Class {@link ExecutorCompletionService} can be used to
65 * write customized variants of these methods.)
67 * <p>The {@link Executors} class provides factory methods for the
68 * executor services provided in this package.
70 * <h3>Usage Examples</h3>
72 * Here is a sketch of a network service in which threads in a thread
73 * pool service incoming requests. It uses the preconfigured {@link
74 * Executors#newFixedThreadPool} factory method:
77 * class NetworkService implements Runnable {
78 * private final ServerSocket serverSocket;
79 * private final ExecutorService pool;
81 * public NetworkService(int port, int poolSize)
82 * throws IOException {
83 * serverSocket = new ServerSocket(port);
84 * pool = Executors.newFixedThreadPool(poolSize);
87 * public void run() { // run the service
90 * pool.execute(new Handler(serverSocket.accept()));
92 * } catch (IOException ex) {
98 * class Handler implements Runnable {
99 * private final Socket socket;
100 * Handler(Socket socket) { this.socket = socket; }
101 * public void run() {
102 * // read and service request on socket
107 * The following method shuts down an <tt>ExecutorService</tt> in two phases,
108 * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
109 * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
112 * void shutdownAndAwaitTermination(ExecutorService pool) {
113 * pool.shutdown(); // Disable new tasks from being submitted
115 * // Wait a while for existing tasks to terminate
116 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
117 * pool.shutdownNow(); // Cancel currently executing tasks
118 * // Wait a while for tasks to respond to being cancelled
119 * if (!pool.awaitTermination(60, TimeUnit.SECONDS))
120 * System.err.println("Pool did not terminate");
122 * } catch (InterruptedException ie) {
123 * // (Re-)Cancel if current thread also interrupted
124 * pool.shutdownNow();
125 * // Preserve interrupt status
126 * Thread.currentThread().interrupt();
131 * <p>Memory consistency effects: Actions in a thread prior to the
132 * submission of a {@code Runnable} or {@code Callable} task to an
133 * {@code ExecutorService}
134 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
135 * any actions taken by that task, which in turn <i>happen-before</i> the
136 * result is retrieved via {@code Future.get()}.
141 public interface ExecutorService extends Executor {
144 * Initiates an orderly shutdown in which previously submitted
145 * tasks are executed, but no new tasks will be accepted.
146 * Invocation has no additional effect if already shut down.
148 * <p>This method does not wait for previously submitted tasks to
149 * complete execution. Use {@link #awaitTermination awaitTermination}
152 * @throws SecurityException if a security manager exists and
153 * shutting down this ExecutorService may manipulate
154 * threads that the caller is not permitted to modify
155 * because it does not hold {@link
156 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
157 * or the security manager's <tt>checkAccess</tt> method
163 * Attempts to stop all actively executing tasks, halts the
164 * processing of waiting tasks, and returns a list of the tasks
165 * that were awaiting execution.
167 * <p>This method does not wait for actively executing tasks to
168 * terminate. Use {@link #awaitTermination awaitTermination} to
171 * <p>There are no guarantees beyond best-effort attempts to stop
172 * processing actively executing tasks. For example, typical
173 * implementations will cancel via {@link Thread#interrupt}, so any
174 * task that fails to respond to interrupts may never terminate.
176 * @return list of tasks that never commenced execution
177 * @throws SecurityException if a security manager exists and
178 * shutting down this ExecutorService may manipulate
179 * threads that the caller is not permitted to modify
180 * because it does not hold {@link
181 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
182 * or the security manager's <tt>checkAccess</tt> method
185 List<Runnable> shutdownNow();
188 * Returns <tt>true</tt> if this executor has been shut down.
190 * @return <tt>true</tt> if this executor has been shut down
192 boolean isShutdown();
195 * Returns <tt>true</tt> if all tasks have completed following shut down.
196 * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
197 * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
199 * @return <tt>true</tt> if all tasks have completed following shut down
201 boolean isTerminated();
204 * Blocks until all tasks have completed execution after a shutdown
205 * request, or the timeout occurs, or the current thread is
206 * interrupted, whichever happens first.
208 * @param timeout the maximum time to wait
209 * @param unit the time unit of the timeout argument
210 * @return <tt>true</tt> if this executor terminated and
211 * <tt>false</tt> if the timeout elapsed before termination
212 * @throws InterruptedException if interrupted while waiting
214 boolean awaitTermination(long timeout, TimeUnit unit)
215 throws InterruptedException;
219 * Submits a value-returning task for execution and returns a
220 * Future representing the pending results of the task. The
221 * Future's <tt>get</tt> method will return the task's result upon
222 * successful completion.
225 * If you would like to immediately block waiting
226 * for a task, you can use constructions of the form
227 * <tt>result = exec.submit(aCallable).get();</tt>
229 * <p> Note: The {@link Executors} class includes a set of methods
230 * that can convert some other common closure-like objects,
231 * for example, {@link java.security.PrivilegedAction} to
232 * {@link Callable} form so they can be submitted.
234 * @param task the task to submit
235 * @return a Future representing pending completion of the task
236 * @throws RejectedExecutionException if the task cannot be
237 * scheduled for execution
238 * @throws NullPointerException if the task is null
240 <T> Future<T> submit(Callable<T> task);
243 * Submits a Runnable task for execution and returns a Future
244 * representing that task. The Future's <tt>get</tt> method will
245 * return the given result upon successful completion.
247 * @param task the task to submit
248 * @param result the result to return
249 * @return a Future representing pending completion of the task
250 * @throws RejectedExecutionException if the task cannot be
251 * scheduled for execution
252 * @throws NullPointerException if the task is null
254 <T> Future<T> submit(Runnable task, T result);
257 * Submits a Runnable task for execution and returns a Future
258 * representing that task. The Future's <tt>get</tt> method will
259 * return <tt>null</tt> upon <em>successful</em> completion.
261 * @param task the task to submit
262 * @return a Future representing pending completion of the task
263 * @throws RejectedExecutionException if the task cannot be
264 * scheduled for execution
265 * @throws NullPointerException if the task is null
267 Future<?> submit(Runnable task);
270 * Executes the given tasks, returning a list of Futures holding
271 * their status and results when all complete.
272 * {@link Future#isDone} is <tt>true</tt> for each
273 * element of the returned list.
274 * Note that a <em>completed</em> task could have
275 * terminated either normally or by throwing an exception.
276 * The results of this method are undefined if the given
277 * collection is modified while this operation is in progress.
279 * @param tasks the collection of tasks
280 * @return A list of Futures representing the tasks, in the same
281 * sequential order as produced by the iterator for the
282 * given task list, each of which has completed.
283 * @throws InterruptedException if interrupted while waiting, in
284 * which case unfinished tasks are cancelled.
285 * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
286 * @throws RejectedExecutionException if any task cannot be
287 * scheduled for execution
290 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
291 throws InterruptedException;
294 * Executes the given tasks, returning a list of Futures holding
295 * their status and results
296 * when all complete or the timeout expires, whichever happens first.
297 * {@link Future#isDone} is <tt>true</tt> for each
298 * element of the returned list.
299 * Upon return, tasks that have not completed are cancelled.
300 * Note that a <em>completed</em> task could have
301 * terminated either normally or by throwing an exception.
302 * The results of this method are undefined if the given
303 * collection is modified while this operation is in progress.
305 * @param tasks the collection of tasks
306 * @param timeout the maximum time to wait
307 * @param unit the time unit of the timeout argument
308 * @return a list of Futures representing the tasks, in the same
309 * sequential order as produced by the iterator for the
310 * given task list. If the operation did not time out,
311 * each task will have completed. If it did time out, some
312 * of these tasks will not have completed.
313 * @throws InterruptedException if interrupted while waiting, in
314 * which case unfinished tasks are cancelled
315 * @throws NullPointerException if tasks, any of its elements, or
316 * unit are <tt>null</tt>
317 * @throws RejectedExecutionException if any task cannot be scheduled
320 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
321 long timeout, TimeUnit unit)
322 throws InterruptedException;
325 * Executes the given tasks, returning the result
326 * of one that has completed successfully (i.e., without throwing
327 * an exception), if any do. Upon normal or exceptional return,
328 * tasks that have not completed are cancelled.
329 * The results of this method are undefined if the given
330 * collection is modified while this operation is in progress.
332 * @param tasks the collection of tasks
333 * @return the result returned by one of the tasks
334 * @throws InterruptedException if interrupted while waiting
335 * @throws NullPointerException if tasks or any element task
336 * subject to execution is <tt>null</tt>
337 * @throws IllegalArgumentException if tasks is empty
338 * @throws ExecutionException if no task successfully completes
339 * @throws RejectedExecutionException if tasks cannot be scheduled
342 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
343 throws InterruptedException, ExecutionException;
346 * Executes the given tasks, returning the result
347 * of one that has completed successfully (i.e., without throwing
348 * an exception), if any do before the given timeout elapses.
349 * Upon normal or exceptional return, tasks that have not
350 * completed are cancelled.
351 * The results of this method are undefined if the given
352 * collection is modified while this operation is in progress.
354 * @param tasks the collection of tasks
355 * @param timeout the maximum time to wait
356 * @param unit the time unit of the timeout argument
357 * @return the result returned by one of the tasks.
358 * @throws InterruptedException if interrupted while waiting
359 * @throws NullPointerException if tasks, or unit, or any element
360 * task subject to execution is <tt>null</tt>
361 * @throws TimeoutException if the given timeout elapses before
362 * any task successfully completes
363 * @throws ExecutionException if no task successfully completes
364 * @throws RejectedExecutionException if tasks cannot be scheduled
367 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
368 long timeout, TimeUnit unit)
369 throws InterruptedException, ExecutionException, TimeoutException;