ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorService.java
Revision: 1.58
Committed: Wed Jan 16 01:59:47 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.57: +31 -31 lines
Log Message:
<tt> -> {@code

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 jsr166 1.51 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.1 */
6    
7     package java.util.concurrent;
8     import java.util.List;
9 dl 1.15 import java.util.Collection;
10 dl 1.1
11     /**
12 dl 1.25 * An {@link Executor} that provides methods to manage termination and
13 dl 1.20 * methods that can produce a {@link Future} for tracking progress of
14 jsr166 1.33 * one or more asynchronous tasks.
15 dl 1.17 *
16 jsr166 1.58 * <p>An {@code ExecutorService} can be shut down, which will cause
17 dl 1.47 * it to reject new tasks. Two different methods are provided for
18 jsr166 1.58 * shutting down an {@code ExecutorService}. The {@link #shutdown}
19 dl 1.47 * 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 jsr166 1.58 * unused {@code ExecutorService} should be shut down to allow
25 dl 1.47 * reclamation of its resources.
26 dl 1.1 *
27 jsr166 1.58 * <p>Method {@code submit} extends base method {@link
28 dl 1.20 * Executor#execute} by creating and returning a {@link Future} that
29     * can be used to cancel execution and/or wait for completion.
30 jsr166 1.58 * Methods {@code invokeAny} and {@code invokeAll} perform the most
31 dl 1.20 * 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 dl 1.17 *
36 dl 1.7 * <p>The {@link Executors} class provides factory methods for the
37     * executor services provided in this package.
38 dl 1.1 *
39 dl 1.47 * <h3>Usage Examples</h3>
40 dl 1.23 *
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 jsr166 1.53 * <pre> {@code
46 dl 1.47 * class NetworkService implements Runnable {
47 jsr166 1.37 * private final ServerSocket serverSocket;
48     * private final ExecutorService pool;
49 dl 1.23 *
50 jsr166 1.37 * public NetworkService(int port, int poolSize)
51     * throws IOException {
52     * serverSocket = new ServerSocket(port);
53     * pool = Executors.newFixedThreadPool(poolSize);
54     * }
55 jsr166 1.33 *
56 dl 1.47 * public void run() { // run the service
57 jsr166 1.37 * try {
58     * for (;;) {
59     * pool.execute(new Handler(serverSocket.accept()));
60     * }
61     * } catch (IOException ex) {
62     * pool.shutdown();
63     * }
64     * }
65     * }
66 dl 1.23 *
67 jsr166 1.37 * class Handler implements Runnable {
68     * private final Socket socket;
69     * Handler(Socket socket) { this.socket = socket; }
70     * public void run() {
71 dl 1.47 * // read and service request on socket
72     * }
73 jsr166 1.53 * }}</pre>
74 dl 1.47 *
75 jsr166 1.58 * 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 dl 1.47 *
79 jsr166 1.53 * <pre> {@code
80 dl 1.47 * 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 jsr166 1.48 * // (Re-)Cancel if current thread also interrupted
92     * pool.shutdownNow();
93     * // Preserve interrupt status
94     * Thread.currentThread().interrupt();
95 jsr166 1.37 * }
96 jsr166 1.53 * }}</pre>
97 brian 1.40 *
98 jsr166 1.43 * <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 brian 1.40 *
105 dl 1.1 * @since 1.5
106 dl 1.5 * @author Doug Lea
107 dl 1.1 */
108     public interface ExecutorService extends Executor {
109 tim 1.8
110 dl 1.17 /**
111     * Initiates an orderly shutdown in which previously submitted
112 jsr166 1.37 * tasks are executed, but no new tasks will be accepted.
113     * Invocation has no additional effect if already shut down.
114     *
115 jsr166 1.49 * <p>This method does not wait for previously submitted tasks to
116     * complete execution. Use {@link #awaitTermination awaitTermination}
117     * to do that.
118     *
119 dl 1.17 * @throws SecurityException if a security manager exists and
120 jsr166 1.37 * shutting down this ExecutorService may manipulate
121     * threads that the caller is not permitted to modify
122     * because it does not hold {@link
123 jsr166 1.58 * java.lang.RuntimePermission}{@code ("modifyThread")},
124     * or the security manager's {@code checkAccess} method
125 jsr166 1.37 * denies access.
126 dl 1.17 */
127     void shutdown();
128    
129     /**
130     * Attempts to stop all actively executing tasks, halts the
131 jsr166 1.49 * 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 jsr166 1.33 *
138 dl 1.17 * <p>There are no guarantees beyond best-effort attempts to stop
139     * processing actively executing tasks. For example, typical
140 jsr166 1.39 * implementations will cancel via {@link Thread#interrupt}, so any
141     * task that fails to respond to interrupts may never terminate.
142 dl 1.17 *
143     * @return list of tasks that never commenced execution
144     * @throws SecurityException if a security manager exists and
145 jsr166 1.37 * shutting down this ExecutorService may manipulate
146     * threads that the caller is not permitted to modify
147     * because it does not hold {@link
148 jsr166 1.58 * java.lang.RuntimePermission}{@code ("modifyThread")},
149     * or the security manager's {@code checkAccess} method
150 jsr166 1.37 * denies access.
151 dl 1.17 */
152     List<Runnable> shutdownNow();
153    
154     /**
155 jsr166 1.58 * Returns {@code true} if this executor has been shut down.
156 dl 1.17 *
157 jsr166 1.58 * @return {@code true} if this executor has been shut down
158 dl 1.17 */
159     boolean isShutdown();
160    
161     /**
162 jsr166 1.58 * 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 dl 1.17 *
166 jsr166 1.58 * @return {@code true} if all tasks have completed following shut down
167 dl 1.17 */
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 jsr166 1.36 * interrupted, whichever happens first.
174 dl 1.17 *
175     * @param timeout the maximum time to wait
176     * @param unit the time unit of the timeout argument
177 jsr166 1.58 * @return {@code true} if this executor terminated and
178     * {@code false} if the timeout elapsed before termination
179 dl 1.17 * @throws InterruptedException if interrupted while waiting
180     */
181     boolean awaitTermination(long timeout, TimeUnit unit)
182     throws InterruptedException;
183    
184 tim 1.8 /**
185 dl 1.30 * Submits a value-returning task for execution and returns a
186 dl 1.31 * Future representing the pending results of the task. The
187 jsr166 1.58 * Future's {@code get} method will return the task's result upon
188 jsr166 1.37 * successful completion.
189 tim 1.8 *
190 dl 1.19 * <p>
191 dl 1.20 * If you would like to immediately block waiting
192 dl 1.19 * for a task, you can use constructions of the form
193 jsr166 1.58 * {@code result = exec.submit(aCallable).get();}
194 dl 1.20 *
195 jsr166 1.56 * <p>Note: The {@link Executors} class includes a set of methods
196 dl 1.20 * 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 tim 1.8 * @param task the task to submit
201     * @return a Future representing pending completion of the task
202 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
203     * scheduled for execution
204     * @throws NullPointerException if the task is null
205 tim 1.8 */
206     <T> Future<T> submit(Callable<T> task);
207    
208     /**
209 dl 1.30 * Submits a Runnable task for execution and returns a Future
210 jsr166 1.58 * representing that task. The Future's {@code get} method will
211 dl 1.31 * return the given result upon successful completion.
212 dl 1.20 *
213     * @param task the task to submit
214     * @param result the result to return
215 dl 1.31 * @return a Future representing pending completion of the task
216 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
217     * scheduled for execution
218     * @throws NullPointerException if the task is null
219 dl 1.20 */
220     <T> Future<T> submit(Runnable task, T result);
221    
222     /**
223 jsr166 1.33 * Submits a Runnable task for execution and returns a Future
224 jsr166 1.58 * representing that task. The Future's {@code get} method will
225     * return {@code null} upon <em>successful</em> completion.
226 dl 1.1 *
227 dl 1.17 * @param task the task to submit
228 dl 1.31 * @return a Future representing pending completion of the task
229 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
230     * scheduled for execution
231     * @throws NullPointerException if the task is null
232 dl 1.1 */
233 dl 1.18 Future<?> submit(Runnable task);
234 dl 1.15
235 dl 1.11 /**
236 dl 1.27 * Executes the given tasks, returning a list of Futures holding
237 jsr166 1.33 * their status and results when all complete.
238 jsr166 1.58 * {@link Future#isDone} is {@code true} for each
239 dl 1.27 * element of the returned list.
240 dl 1.12 * Note that a <em>completed</em> task could have
241     * terminated either normally or by throwing an exception.
242 dl 1.21 * The results of this method are undefined if the given
243     * collection is modified while this operation is in progress.
244 jsr166 1.37 *
245 dl 1.11 * @param tasks the collection of tasks
246 dl 1.13 * @return A list of Futures representing the tasks, in the same
247 jsr166 1.37 * sequential order as produced by the iterator for the
248     * given task list, each of which has completed.
249 dl 1.11 * @throws InterruptedException if interrupted while waiting, in
250 jsr166 1.37 * which case unfinished tasks are cancelled.
251 jsr166 1.58 * @throws NullPointerException if tasks or any of its elements are {@code null}
252 jsr166 1.37 * @throws RejectedExecutionException if any task cannot be
253     * scheduled for execution
254 dl 1.11 */
255 jsr166 1.38 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
256 dl 1.11 throws InterruptedException;
257    
258     /**
259 dl 1.27 * Executes the given tasks, returning a list of Futures holding
260 jsr166 1.33 * their status and results
261 dl 1.15 * when all complete or the timeout expires, whichever happens first.
262 jsr166 1.58 * {@link Future#isDone} is {@code true} for each
263 dl 1.27 * element of the returned list.
264 dl 1.11 * Upon return, tasks that have not completed are cancelled.
265 dl 1.12 * Note that a <em>completed</em> task could have
266     * terminated either normally or by throwing an exception.
267 dl 1.21 * The results of this method are undefined if the given
268     * collection is modified while this operation is in progress.
269 jsr166 1.37 *
270 dl 1.11 * @param tasks the collection of tasks
271     * @param timeout the maximum time to wait
272 dl 1.15 * @param unit the time unit of the timeout argument
273 jsr166 1.37 * @return a list of Futures representing the tasks, in the same
274     * sequential order as produced by the iterator for the
275     * given task list. If the operation did not time out,
276     * each task will have completed. If it did time out, some
277     * of these tasks will not have completed.
278 dl 1.11 * @throws InterruptedException if interrupted while waiting, in
279 jsr166 1.37 * which case unfinished tasks are cancelled
280 dl 1.17 * @throws NullPointerException if tasks, any of its elements, or
281 jsr166 1.58 * unit are {@code null}
282 dl 1.13 * @throws RejectedExecutionException if any task cannot be scheduled
283 jsr166 1.37 * for execution
284 dl 1.11 */
285 jsr166 1.38 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
286 jsr166 1.33 long timeout, TimeUnit unit)
287 dl 1.11 throws InterruptedException;
288    
289     /**
290 dl 1.17 * Executes the given tasks, returning the result
291 dl 1.15 * of one that has completed successfully (i.e., without throwing
292     * an exception), if any do. Upon normal or exceptional return,
293     * tasks that have not completed are cancelled.
294 dl 1.21 * The results of this method are undefined if the given
295     * collection is modified while this operation is in progress.
296 jsr166 1.37 *
297 dl 1.11 * @param tasks the collection of tasks
298 jsr166 1.37 * @return the result returned by one of the tasks
299 dl 1.15 * @throws InterruptedException if interrupted while waiting
300 jsr166 1.50 * @throws NullPointerException if tasks or any element task
301 jsr166 1.58 * subject to execution is {@code null}
302 jsr166 1.37 * @throws IllegalArgumentException if tasks is empty
303 dl 1.15 * @throws ExecutionException if no task successfully completes
304     * @throws RejectedExecutionException if tasks cannot be scheduled
305 jsr166 1.37 * for execution
306 dl 1.11 */
307 jsr166 1.38 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
308 dl 1.15 throws InterruptedException, ExecutionException;
309 dl 1.11
310     /**
311 dl 1.17 * Executes the given tasks, returning the result
312 dl 1.15 * of one that has completed successfully (i.e., without throwing
313     * an exception), if any do before the given timeout elapses.
314     * Upon normal or exceptional return, tasks that have not
315     * completed are cancelled.
316 dl 1.21 * The results of this method are undefined if the given
317     * collection is modified while this operation is in progress.
318 jsr166 1.37 *
319 dl 1.11 * @param tasks the collection of tasks
320     * @param timeout the maximum time to wait
321     * @param unit the time unit of the timeout argument
322 jsr166 1.57 * @return the result returned by one of the tasks
323 dl 1.15 * @throws InterruptedException if interrupted while waiting
324 jsr166 1.50 * @throws NullPointerException if tasks, or unit, or any element
325 jsr166 1.58 * task subject to execution is {@code null}
326 dl 1.15 * @throws TimeoutException if the given timeout elapses before
327 jsr166 1.37 * any task successfully completes
328 dl 1.15 * @throws ExecutionException if no task successfully completes
329     * @throws RejectedExecutionException if tasks cannot be scheduled
330 jsr166 1.37 * for execution
331 dl 1.11 */
332 jsr166 1.38 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
333 jsr166 1.33 long timeout, TimeUnit unit)
334 dl 1.15 throws InterruptedException, ExecutionException, TimeoutException;
335 dl 1.1 }