ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorService.java
Revision: 1.47
Committed: Fri Jul 14 11:01:44 2006 UTC (17 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.46: +36 -11 lines
Log Message:
Improve documentation about shutdown

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