ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ExecutorService.java
Revision: 1.6
Committed: Sun Jan 18 20:17:32 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.5: +1 -0 lines
Log Message:
exactly one blank line before and after package statements

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