ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorService.java
Revision: 1.48
Committed: Mon Jul 17 02:55:01 2006 UTC (17 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.47: +4 -2 lines
Log Message:
html layout

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 jsr166 1.48 * // (Re-)Cancel if current thread also interrupted
95     * pool.shutdownNow();
96     * // Preserve interrupt status
97     * Thread.currentThread().interrupt();
98 jsr166 1.37 * }
99 dl 1.23 * }
100     * </pre>
101 brian 1.40 *
102 jsr166 1.43 * <p>Memory consistency effects: Actions in a thread prior to the
103     * submission of a {@code Runnable} or {@code Callable} task to an
104     * {@code ExecutorService}
105     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
106     * any actions taken by that task, which in turn <i>happen-before</i> the
107     * result is retrieved via {@code Future.get()}.
108 brian 1.40 *
109 dl 1.1 * @since 1.5
110 dl 1.5 * @author Doug Lea
111 dl 1.1 */
112     public interface ExecutorService extends Executor {
113 tim 1.8
114 dl 1.17 /**
115     * Initiates an orderly shutdown in which previously submitted
116 jsr166 1.37 * tasks are executed, but no new tasks will be accepted.
117     * Invocation has no additional effect if already shut down.
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     * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
124     * or the security manager's <tt>checkAccess</tt> method
125     * denies access.
126 dl 1.17 */
127     void shutdown();
128    
129     /**
130     * Attempts to stop all actively executing tasks, halts the
131     * processing of waiting tasks, and returns a list of the tasks that were
132 jsr166 1.33 * awaiting execution.
133     *
134 dl 1.17 * <p>There are no guarantees beyond best-effort attempts to stop
135     * processing actively executing tasks. For example, typical
136 jsr166 1.39 * implementations will cancel via {@link Thread#interrupt}, so any
137     * task that fails to respond to interrupts may never terminate.
138 dl 1.17 *
139     * @return list of tasks that never commenced execution
140     * @throws SecurityException if a security manager exists and
141 jsr166 1.37 * shutting down this ExecutorService may manipulate
142     * threads that the caller is not permitted to modify
143     * because it does not hold {@link
144     * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
145     * or the security manager's <tt>checkAccess</tt> method
146     * denies access.
147 dl 1.17 */
148     List<Runnable> shutdownNow();
149    
150     /**
151     * Returns <tt>true</tt> if this executor has been shut down.
152     *
153     * @return <tt>true</tt> if this executor has been shut down
154     */
155     boolean isShutdown();
156    
157     /**
158     * Returns <tt>true</tt> if all tasks have completed following shut down.
159     * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
160     * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
161     *
162     * @return <tt>true</tt> if all tasks have completed following shut down
163     */
164     boolean isTerminated();
165    
166     /**
167     * Blocks until all tasks have completed execution after a shutdown
168     * request, or the timeout occurs, or the current thread is
169 jsr166 1.36 * interrupted, whichever happens first.
170 dl 1.17 *
171     * @param timeout the maximum time to wait
172     * @param unit the time unit of the timeout argument
173 jsr166 1.37 * @return <tt>true</tt> if this executor terminated and
174     * <tt>false</tt> if the timeout elapsed before termination
175 dl 1.17 * @throws InterruptedException if interrupted while waiting
176     */
177     boolean awaitTermination(long timeout, TimeUnit unit)
178     throws InterruptedException;
179    
180    
181 tim 1.8 /**
182 dl 1.30 * Submits a value-returning task for execution and returns a
183 dl 1.31 * Future representing the pending results of the task. The
184 dl 1.32 * Future's <tt>get</tt> method will return the task's result upon
185 jsr166 1.37 * successful completion.
186 tim 1.8 *
187 dl 1.19 * <p>
188 dl 1.20 * If you would like to immediately block waiting
189 dl 1.19 * for a task, you can use constructions of the form
190     * <tt>result = exec.submit(aCallable).get();</tt>
191 dl 1.20 *
192     * <p> Note: The {@link Executors} class includes a set of methods
193     * that can convert some other common closure-like objects,
194     * for example, {@link java.security.PrivilegedAction} to
195     * {@link Callable} form so they can be submitted.
196     *
197 tim 1.8 * @param task the task to submit
198     * @return a Future representing pending completion of the task
199 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
200     * scheduled for execution
201     * @throws NullPointerException if the task is null
202 tim 1.8 */
203     <T> Future<T> submit(Callable<T> task);
204    
205     /**
206 dl 1.30 * Submits a Runnable task for execution and returns a Future
207 jsr166 1.33 * representing that task. The Future's <tt>get</tt> method will
208 dl 1.31 * return the given result upon successful completion.
209 dl 1.20 *
210     * @param task the task to submit
211     * @param result the result to return
212 dl 1.31 * @return a Future representing pending completion of the task
213 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
214     * scheduled for execution
215     * @throws NullPointerException if the task is null
216 dl 1.20 */
217     <T> Future<T> submit(Runnable task, T result);
218    
219     /**
220 jsr166 1.33 * Submits a Runnable task for execution and returns a Future
221     * representing that task. The Future's <tt>get</tt> method will
222 jsr166 1.37 * return <tt>null</tt> upon <em>successful</em> completion.
223 dl 1.1 *
224 dl 1.17 * @param task the task to submit
225 dl 1.31 * @return a Future representing pending completion of the task
226 jsr166 1.37 * @throws RejectedExecutionException if the task cannot be
227     * scheduled for execution
228     * @throws NullPointerException if the task is null
229 dl 1.1 */
230 dl 1.18 Future<?> submit(Runnable task);
231 dl 1.15
232 dl 1.11 /**
233 dl 1.27 * Executes the given tasks, returning a list of Futures holding
234 jsr166 1.33 * their status and results when all complete.
235     * {@link Future#isDone} is <tt>true</tt> for each
236 dl 1.27 * element of the returned list.
237 dl 1.12 * Note that a <em>completed</em> task could have
238     * terminated either normally or by throwing an exception.
239 dl 1.21 * The results of this method are undefined if the given
240     * collection is modified while this operation is in progress.
241 jsr166 1.37 *
242 dl 1.11 * @param tasks the collection of tasks
243 dl 1.13 * @return A list of Futures representing the tasks, in the same
244 jsr166 1.37 * sequential order as produced by the iterator for the
245     * given task list, each of which has completed.
246 dl 1.11 * @throws InterruptedException if interrupted while waiting, in
247 jsr166 1.37 * which case unfinished tasks are cancelled.
248 dl 1.13 * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
249 jsr166 1.37 * @throws RejectedExecutionException if any task cannot be
250     * scheduled for execution
251 dl 1.11 */
252 jsr166 1.38
253     <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
254 dl 1.11 throws InterruptedException;
255    
256     /**
257 dl 1.27 * Executes the given tasks, returning a list of Futures holding
258 jsr166 1.33 * their status and results
259 dl 1.15 * when all complete or the timeout expires, whichever happens first.
260 jsr166 1.33 * {@link Future#isDone} is <tt>true</tt> for each
261 dl 1.27 * element of the returned list.
262 dl 1.11 * Upon return, tasks that have not completed are cancelled.
263 dl 1.12 * Note that a <em>completed</em> task could have
264     * terminated either normally or by throwing an exception.
265 dl 1.21 * The results of this method are undefined if the given
266     * collection is modified while this operation is in progress.
267 jsr166 1.37 *
268 dl 1.11 * @param tasks the collection of tasks
269     * @param timeout the maximum time to wait
270 dl 1.15 * @param unit the time unit of the timeout argument
271 jsr166 1.37 * @return a list of Futures representing the tasks, in the same
272     * sequential order as produced by the iterator for the
273     * given task list. If the operation did not time out,
274     * each task will have completed. If it did time out, some
275     * of these tasks will not have completed.
276 dl 1.11 * @throws InterruptedException if interrupted while waiting, in
277 jsr166 1.37 * which case unfinished tasks are cancelled
278 dl 1.17 * @throws NullPointerException if tasks, any of its elements, or
279 jsr166 1.37 * unit are <tt>null</tt>
280 dl 1.13 * @throws RejectedExecutionException if any task cannot be scheduled
281 jsr166 1.37 * for execution
282 dl 1.11 */
283 jsr166 1.38 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
284 jsr166 1.33 long timeout, TimeUnit unit)
285 dl 1.11 throws InterruptedException;
286    
287     /**
288 dl 1.17 * Executes the given tasks, returning the result
289 dl 1.15 * of one that has completed successfully (i.e., without throwing
290     * an exception), if any do. Upon normal or exceptional return,
291     * tasks that have not completed are cancelled.
292 dl 1.21 * The results of this method are undefined if the given
293     * collection is modified while this operation is in progress.
294 jsr166 1.37 *
295 dl 1.11 * @param tasks the collection of tasks
296 jsr166 1.37 * @return the result returned by one of the tasks
297 dl 1.15 * @throws InterruptedException if interrupted while waiting
298     * @throws NullPointerException if tasks or any of its elements
299 jsr166 1.37 * are <tt>null</tt>
300     * @throws IllegalArgumentException if tasks is empty
301 dl 1.15 * @throws ExecutionException if no task successfully completes
302     * @throws RejectedExecutionException if tasks cannot be scheduled
303 jsr166 1.37 * for execution
304 dl 1.11 */
305 jsr166 1.38 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
306 dl 1.15 throws InterruptedException, ExecutionException;
307 dl 1.11
308     /**
309 dl 1.17 * Executes the given tasks, returning the result
310 dl 1.15 * of one that has completed successfully (i.e., without throwing
311     * an exception), if any do before the given timeout elapses.
312     * Upon normal or exceptional return, tasks that have not
313     * completed are cancelled.
314 dl 1.21 * The results of this method are undefined if the given
315     * collection is modified while this operation is in progress.
316 jsr166 1.37 *
317 dl 1.11 * @param tasks the collection of tasks
318     * @param timeout the maximum time to wait
319     * @param unit the time unit of the timeout argument
320 jsr166 1.37 * @return the result returned by one of the tasks.
321 dl 1.15 * @throws InterruptedException if interrupted while waiting
322 dl 1.17 * @throws NullPointerException if tasks, any of its elements, or
323 jsr166 1.37 * unit are <tt>null</tt>
324 dl 1.15 * @throws TimeoutException if the given timeout elapses before
325 jsr166 1.37 * any task successfully completes
326 dl 1.15 * @throws ExecutionException if no task successfully completes
327     * @throws RejectedExecutionException if tasks cannot be scheduled
328 jsr166 1.37 * for execution
329 dl 1.11 */
330 jsr166 1.38 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
331 jsr166 1.33 long timeout, TimeUnit unit)
332 dl 1.15 throws InterruptedException, ExecutionException, TimeoutException;
333 dl 1.1 }