ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorService.java
Revision: 1.61
Committed: Thu Jul 18 17:13:42 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +6 -0 lines
Log Message:
doclint warning fixes

File Contents

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