ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorService.java
Revision: 1.52
Committed: Wed Jun 8 00:50:35 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.51: +0 -2 lines
Log Message:
clean up imports

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 <tt>ExecutorService</tt> can be shut down, which will cause
17 * it to reject new tasks. Two different methods are provided for
18 * shutting down an <tt>ExecutorService</tt>. 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 <tt>ExecutorService</tt> should be shut down to allow
25 * reclamation of its resources.
26 *
27 * <p> Method <tt>submit</tt> extends base method {@link
28 * Executor#execute} by creating and returning a {@link Future} that
29 * can be used to cancel execution and/or wait for completion.
30 * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> 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>
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 * }
74 * </pre>
75 *
76 * The following method shuts down an <tt>ExecutorService</tt> in two phases,
77 * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
78 * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
79 *
80 * <pre>
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 * }
98 * </pre>
99 *
100 * <p>Memory consistency effects: Actions in a thread prior to the
101 * submission of a {@code Runnable} or {@code Callable} task to an
102 * {@code ExecutorService}
103 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
104 * any actions taken by that task, which in turn <i>happen-before</i> the
105 * result is retrieved via {@code Future.get()}.
106 *
107 * @since 1.5
108 * @author Doug Lea
109 */
110 public interface ExecutorService extends Executor {
111
112 /**
113 * Initiates an orderly shutdown in which previously submitted
114 * tasks are executed, but no new tasks will be accepted.
115 * Invocation has no additional effect if already shut down.
116 *
117 * <p>This method does not wait for previously submitted tasks to
118 * complete execution. Use {@link #awaitTermination awaitTermination}
119 * to do that.
120 *
121 * @throws SecurityException if a security manager exists and
122 * shutting down this ExecutorService may manipulate
123 * threads that the caller is not permitted to modify
124 * because it does not hold {@link
125 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
126 * or the security manager's <tt>checkAccess</tt> method
127 * denies access.
128 */
129 void shutdown();
130
131 /**
132 * Attempts to stop all actively executing tasks, halts the
133 * processing of waiting tasks, and returns a list of the tasks
134 * that were awaiting execution.
135 *
136 * <p>This method does not wait for actively executing tasks to
137 * terminate. Use {@link #awaitTermination awaitTermination} to
138 * do that.
139 *
140 * <p>There are no guarantees beyond best-effort attempts to stop
141 * processing actively executing tasks. For example, typical
142 * implementations will cancel via {@link Thread#interrupt}, so any
143 * task that fails to respond to interrupts may never terminate.
144 *
145 * @return list of tasks that never commenced execution
146 * @throws SecurityException if a security manager exists and
147 * shutting down this ExecutorService may manipulate
148 * threads that the caller is not permitted to modify
149 * because it does not hold {@link
150 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
151 * or the security manager's <tt>checkAccess</tt> method
152 * denies access.
153 */
154 List<Runnable> shutdownNow();
155
156 /**
157 * Returns <tt>true</tt> if this executor has been shut down.
158 *
159 * @return <tt>true</tt> if this executor has been shut down
160 */
161 boolean isShutdown();
162
163 /**
164 * Returns <tt>true</tt> if all tasks have completed following shut down.
165 * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
166 * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
167 *
168 * @return <tt>true</tt> if all tasks have completed following shut down
169 */
170 boolean isTerminated();
171
172 /**
173 * Blocks until all tasks have completed execution after a shutdown
174 * request, or the timeout occurs, or the current thread is
175 * interrupted, whichever happens first.
176 *
177 * @param timeout the maximum time to wait
178 * @param unit the time unit of the timeout argument
179 * @return <tt>true</tt> if this executor terminated and
180 * <tt>false</tt> if the timeout elapsed before termination
181 * @throws InterruptedException if interrupted while waiting
182 */
183 boolean awaitTermination(long timeout, TimeUnit unit)
184 throws InterruptedException;
185
186
187 /**
188 * Submits a value-returning task for execution and returns a
189 * Future representing the pending results of the task. The
190 * Future's <tt>get</tt> method will return the task's result upon
191 * successful completion.
192 *
193 * <p>
194 * If you would like to immediately block waiting
195 * for a task, you can use constructions of the form
196 * <tt>result = exec.submit(aCallable).get();</tt>
197 *
198 * <p> Note: The {@link Executors} class includes a set of methods
199 * that can convert some other common closure-like objects,
200 * for example, {@link java.security.PrivilegedAction} to
201 * {@link Callable} form so they can be submitted.
202 *
203 * @param task the task to submit
204 * @return a Future representing pending completion of the task
205 * @throws RejectedExecutionException if the task cannot be
206 * scheduled for execution
207 * @throws NullPointerException if the task is null
208 */
209 <T> Future<T> submit(Callable<T> task);
210
211 /**
212 * Submits a Runnable task for execution and returns a Future
213 * representing that task. The Future's <tt>get</tt> method will
214 * return the given result upon successful completion.
215 *
216 * @param task the task to submit
217 * @param result the result to return
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 <tt>get</tt> method will
228 * return <tt>null</tt> 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 <tt>true</tt> 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 * @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 <tt>null</tt>
255 * @throws RejectedExecutionException if any task cannot be
256 * scheduled for execution
257 */
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 <tt>true</tt> 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 * @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 <tt>null</tt>
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 * @return the result returned by one of the tasks
303 * @throws InterruptedException if interrupted while waiting
304 * @throws NullPointerException if tasks or any element task
305 * subject to execution is <tt>null</tt>
306 * @throws IllegalArgumentException if tasks is empty
307 * @throws ExecutionException if no task successfully completes
308 * @throws RejectedExecutionException if tasks cannot be scheduled
309 * for execution
310 */
311 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
312 throws InterruptedException, ExecutionException;
313
314 /**
315 * Executes the given tasks, returning the result
316 * of one that has completed successfully (i.e., without throwing
317 * an exception), if any do before the given timeout elapses.
318 * Upon normal or exceptional return, tasks that have not
319 * completed are cancelled.
320 * The results of this method are undefined if the given
321 * collection is modified while this operation is in progress.
322 *
323 * @param tasks the collection of tasks
324 * @param timeout the maximum time to wait
325 * @param unit the time unit of the timeout argument
326 * @return the result returned by one of the tasks.
327 * @throws InterruptedException if interrupted while waiting
328 * @throws NullPointerException if tasks, or unit, or any element
329 * task subject to execution is <tt>null</tt>
330 * @throws TimeoutException if the given timeout elapses before
331 * any task successfully completes
332 * @throws ExecutionException if no task successfully completes
333 * @throws RejectedExecutionException if tasks cannot be scheduled
334 * for execution
335 */
336 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
337 long timeout, TimeUnit unit)
338 throws InterruptedException, ExecutionException, TimeoutException;
339 }