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