ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ExecutorService.java
Revision: 1.64
Committed: Thu Mar 7 00:50:36 2019 UTC (5 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.63: +1 -1 lines
Log Message:
8220248: fix headings in java.util.concurrent

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