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, 10 months ago) by dl
Branch: MAIN
Changes since 1.46: +36 -11 lines
Log Message:
Improve documentation about shutdown

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.22 * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5 dl 1.1 */
6    
7     package java.util.concurrent;
8     import java.util.List;
9 dl 1.15 import java.util.Collection;
10 tim 1.8 import java.security.PrivilegedAction;
11     import java.security.PrivilegedExceptionAction;
12 dl 1.1
13     /**
14 dl 1.25 * An {@link Executor} that provides methods to manage termination and
15 dl 1.20 * methods that can produce a {@link Future} for tracking progress of
16 jsr166 1.33 * one or more asynchronous tasks.
17 dl 1.17 *
18 dl 1.47 * <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 dl 1.1 *
29 dl 1.20 * <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 dl 1.17 *
38 dl 1.7 * <p>The {@link Executors} class provides factory methods for the
39     * executor services provided in this package.
40 dl 1.1 *
41 dl 1.47 * <h3>Usage Examples</h3>
42 dl 1.23 *
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 dl 1.47 * class NetworkService implements Runnable {
49 jsr166 1.37 * private final ServerSocket serverSocket;
50     * private final ExecutorService pool;
51 dl 1.23 *
52 jsr166 1.37 * public NetworkService(int port, int poolSize)
53     * throws IOException {
54     * serverSocket = new ServerSocket(port);
55     * pool = Executors.newFixedThreadPool(poolSize);
56     * }
57 jsr166 1.33 *
58 dl 1.47 * public void run() { // run the service
59 jsr166 1.37 * try {
60     * for (;;) {
61     * pool.execute(new Handler(serverSocket.accept()));
62     * }
63     * } catch (IOException ex) {
64     * pool.shutdown();
65     * }
66     * }
67     * }
68 dl 1.23 *
69 jsr166 1.37 * class Handler implements Runnable {
70     * private final Socket socket;
71     * Handler(Socket socket) { this.socket = socket; }
72     * public void run() {
73 dl 1.47 * // 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 jsr166 1.37 * }
97 dl 1.23 * }
98     * </pre>
99 brian 1.40 *
100 jsr166 1.43 * <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 brian 1.40 *
107 dl 1.1 * @since 1.5
108 dl 1.5 * @author Doug Lea
109 dl 1.1 */
110     public interface ExecutorService extends Executor {
111 tim 1.8
112 dl 1.17 /**
113     * Initiates an orderly shutdown in which previously submitted
114 jsr166 1.37 * tasks are executed, but no new tasks will be accepted.
115     * Invocation has no additional effect if already shut down.
116     *
117 dl 1.17 * @throws SecurityException if a security manager exists and
118 jsr166 1.37 * 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 dl 1.17 */
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 jsr166 1.33 * awaiting execution.
131     *
132 dl 1.17 * <p>There are no guarantees beyond best-effort attempts to stop
133     * processing actively executing tasks. For example, typical
134 jsr166 1.39 * implementations will cancel via {@link Thread#interrupt}, so any
135     * task that fails to respond to interrupts may never terminate.
136 dl 1.17 *
137     * @return list of tasks that never commenced execution
138     * @throws SecurityException if a security manager exists and
139 jsr166 1.37 * 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 dl 1.17 */
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 jsr166 1.36 * interrupted, whichever happens first.
168 dl 1.17 *
169     * @param timeout the maximum time to wait
170     * @param unit the time unit of the timeout argument
171 jsr166 1.37 * @return <tt>true</tt> if this executor terminated and
172     * <tt>false</tt> if the timeout elapsed before termination
173 dl 1.17 * @throws InterruptedException if interrupted while waiting
174     */
175     boolean awaitTermination(long timeout, TimeUnit unit)
176     throws InterruptedException;
177    
178    
179 tim 1.8 /**
180 dl 1.30 * Submits a value-returning task for execution and returns a
181 dl 1.31 * Future representing the pending results of the task. The
182 dl 1.32 * Future's <tt>get</tt> method will return the task's result upon
183 jsr166 1.37 * successful completion.
184 tim 1.8 *
185 dl 1.19 * <p>
186 dl 1.20 * If you would like to immediately block waiting
187 dl 1.19 * for a task, you can use constructions of the form
188     * <tt>result = exec.submit(aCallable).get();</tt>
189 dl 1.20 *
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 tim 1.8 * @param task the task to submit
196     * @return a Future representing pending completion of the task
197 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
198     * scheduled for execution
199     * @throws NullPointerException if the task is null
200 tim 1.8 */
201     <T> Future<T> submit(Callable<T> task);
202    
203     /**
204 dl 1.30 * Submits a Runnable task for execution and returns a Future
205 jsr166 1.33 * representing that task. The Future's <tt>get</tt> method will
206 dl 1.31 * return the given result upon successful completion.
207 dl 1.20 *
208     * @param task the task to submit
209     * @param result the result to return
210 dl 1.31 * @return a Future representing pending completion of the task
211 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
212     * scheduled for execution
213     * @throws NullPointerException if the task is null
214 dl 1.20 */
215     <T> Future<T> submit(Runnable task, T result);
216    
217     /**
218 jsr166 1.33 * Submits a Runnable task for execution and returns a Future
219     * representing that task. The Future's <tt>get</tt> method will
220 jsr166 1.37 * return <tt>null</tt> upon <em>successful</em> completion.
221 dl 1.1 *
222 dl 1.17 * @param task the task to submit
223 dl 1.31 * @return a Future representing pending completion of the task
224 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
225     * scheduled for execution
226     * @throws NullPointerException if the task is null
227 dl 1.1 */
228 dl 1.18 Future<?> submit(Runnable task);
229 dl 1.15
230 dl 1.11 /**
231 dl 1.27 * Executes the given tasks, returning a list of Futures holding
232 jsr166 1.33 * their status and results when all complete.
233     * {@link Future#isDone} is <tt>true</tt> for each
234 dl 1.27 * element of the returned list.
235 dl 1.12 * Note that a <em>completed</em> task could have
236     * terminated either normally or by throwing an exception.
237 dl 1.21 * The results of this method are undefined if the given
238     * collection is modified while this operation is in progress.
239 jsr166 1.37 *
240 dl 1.11 * @param tasks the collection of tasks
241 dl 1.13 * @return A list of Futures representing the tasks, in the same
242 jsr166 1.37 * sequential order as produced by the iterator for the
243     * given task list, each of which has completed.
244 dl 1.11 * @throws InterruptedException if interrupted while waiting, in
245 jsr166 1.37 * which case unfinished tasks are cancelled.
246 dl 1.13 * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
247 jsr166 1.37 * @throws RejectedExecutionException if any task cannot be
248     * scheduled for execution
249 dl 1.11 */
250 jsr166 1.38
251     <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
252 dl 1.11 throws InterruptedException;
253    
254     /**
255 dl 1.27 * Executes the given tasks, returning a list of Futures holding
256 jsr166 1.33 * their status and results
257 dl 1.15 * when all complete or the timeout expires, whichever happens first.
258 jsr166 1.33 * {@link Future#isDone} is <tt>true</tt> for each
259 dl 1.27 * element of the returned list.
260 dl 1.11 * Upon return, tasks that have not completed are cancelled.
261 dl 1.12 * Note that a <em>completed</em> task could have
262     * terminated either normally or by throwing an exception.
263 dl 1.21 * The results of this method are undefined if the given
264     * collection is modified while this operation is in progress.
265 jsr166 1.37 *
266 dl 1.11 * @param tasks the collection of tasks
267     * @param timeout the maximum time to wait
268 dl 1.15 * @param unit the time unit of the timeout argument
269 jsr166 1.37 * @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 dl 1.11 * @throws InterruptedException if interrupted while waiting, in
275 jsr166 1.37 * which case unfinished tasks are cancelled
276 dl 1.17 * @throws NullPointerException if tasks, any of its elements, or
277 jsr166 1.37 * unit are <tt>null</tt>
278 dl 1.13 * @throws RejectedExecutionException if any task cannot be scheduled
279 jsr166 1.37 * for execution
280 dl 1.11 */
281 jsr166 1.38 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
282 jsr166 1.33 long timeout, TimeUnit unit)
283 dl 1.11 throws InterruptedException;
284    
285     /**
286 dl 1.17 * Executes the given tasks, returning the result
287 dl 1.15 * 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 dl 1.21 * The results of this method are undefined if the given
291     * collection is modified while this operation is in progress.
292 jsr166 1.37 *
293 dl 1.11 * @param tasks the collection of tasks
294 jsr166 1.37 * @return the result returned by one of the tasks
295 dl 1.15 * @throws InterruptedException if interrupted while waiting
296     * @throws NullPointerException if tasks or any of its elements
297 jsr166 1.37 * are <tt>null</tt>
298     * @throws IllegalArgumentException if tasks is empty
299 dl 1.15 * @throws ExecutionException if no task successfully completes
300     * @throws RejectedExecutionException if tasks cannot be scheduled
301 jsr166 1.37 * for execution
302 dl 1.11 */
303 jsr166 1.38 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
304 dl 1.15 throws InterruptedException, ExecutionException;
305 dl 1.11
306     /**
307 dl 1.17 * Executes the given tasks, returning the result
308 dl 1.15 * 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 dl 1.21 * The results of this method are undefined if the given
313     * collection is modified while this operation is in progress.
314 jsr166 1.37 *
315 dl 1.11 * @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 jsr166 1.37 * @return the result returned by one of the tasks.
319 dl 1.15 * @throws InterruptedException if interrupted while waiting
320 dl 1.17 * @throws NullPointerException if tasks, any of its elements, or
321 jsr166 1.37 * unit are <tt>null</tt>
322 dl 1.15 * @throws TimeoutException if the given timeout elapses before
323 jsr166 1.37 * any task successfully completes
324 dl 1.15 * @throws ExecutionException if no task successfully completes
325     * @throws RejectedExecutionException if tasks cannot be scheduled
326 jsr166 1.37 * for execution
327 dl 1.11 */
328 jsr166 1.38 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
329 jsr166 1.33 long timeout, TimeUnit unit)
330 dl 1.15 throws InterruptedException, ExecutionException, TimeoutException;
331 dl 1.1 }