blob: 8d7ec6d4e3621863807419b92e7bb718d84dffb9 [file] [log] [blame]
Aurimas Liutikas88c7ff12023-08-10 12:42:26 -07001/*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25/*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
34 */
35
36package java.util.concurrent;
37
38import java.util.Collection;
39import java.util.List;
40
41// BEGIN android-note
42// removed security manager docs
43// END android-note
44
45/**
46 * An {@link Executor} that provides methods to manage termination and
47 * methods that can produce a {@link Future} for tracking progress of
48 * one or more asynchronous tasks.
49 *
50 * <p>An {@code ExecutorService} can be shut down, which will cause
51 * it to reject new tasks. Two different methods are provided for
52 * shutting down an {@code ExecutorService}. The {@link #shutdown}
53 * method will allow previously submitted tasks to execute before
54 * terminating, while the {@link #shutdownNow} method prevents waiting
55 * tasks from starting and attempts to stop currently executing tasks.
56 * Upon termination, an executor has no tasks actively executing, no
57 * tasks awaiting execution, and no new tasks can be submitted. An
58 * unused {@code ExecutorService} should be shut down to allow
59 * reclamation of its resources.
60 *
61 * <p>Method {@code submit} extends base method {@link
62 * Executor#execute(Runnable)} by creating and returning a {@link Future}
63 * that can be used to cancel execution and/or wait for completion.
64 * Methods {@code invokeAny} and {@code invokeAll} perform the most
65 * commonly useful forms of bulk execution, executing a collection of
66 * tasks and then waiting for at least one, or all, to
67 * complete. (Class {@link ExecutorCompletionService} can be used to
68 * write customized variants of these methods.)
69 *
70 * <p>The {@link Executors} class provides factory methods for the
71 * executor services provided in this package.
72 *
73 * <h2>Usage Examples</h2>
74 *
75 * Here is a sketch of a network service in which threads in a thread
76 * pool service incoming requests. It uses the preconfigured {@link
77 * Executors#newFixedThreadPool} factory method:
78 *
79 * <pre> {@code
80 * class NetworkService implements Runnable {
81 * private final ServerSocket serverSocket;
82 * private final ExecutorService pool;
83 *
84 * public NetworkService(int port, int poolSize)
85 * throws IOException {
86 * serverSocket = new ServerSocket(port);
87 * pool = Executors.newFixedThreadPool(poolSize);
88 * }
89 *
90 * public void run() { // run the service
91 * try {
92 * for (;;) {
93 * pool.execute(new Handler(serverSocket.accept()));
94 * }
95 * } catch (IOException ex) {
96 * pool.shutdown();
97 * }
98 * }
99 * }
100 *
101 * class Handler implements Runnable {
102 * private final Socket socket;
103 * Handler(Socket socket) { this.socket = socket; }
104 * public void run() {
105 * // read and service request on socket
106 * }
107 * }}</pre>
108 *
109 * The following method shuts down an {@code ExecutorService} in two phases,
110 * first by calling {@code shutdown} to reject incoming tasks, and then
111 * calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
112 *
113 * <pre> {@code
114 * void shutdownAndAwaitTermination(ExecutorService pool) {
115 * pool.shutdown(); // Disable new tasks from being submitted
116 * try {
117 * // Wait a while for existing tasks to terminate
118 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
119 * pool.shutdownNow(); // Cancel currently executing tasks
120 * // Wait a while for tasks to respond to being cancelled
121 * if (!pool.awaitTermination(60, TimeUnit.SECONDS))
122 * System.err.println("Pool did not terminate");
123 * }
124 * } catch (InterruptedException ex) {
125 * // (Re-)Cancel if current thread also interrupted
126 * pool.shutdownNow();
127 * // Preserve interrupt status
128 * Thread.currentThread().interrupt();
129 * }
130 * }}</pre>
131 *
132 * <p>Memory consistency effects: Actions in a thread prior to the
133 * submission of a {@code Runnable} or {@code Callable} task to an
134 * {@code ExecutorService}
135 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
136 * any actions taken by that task, which in turn <i>happen-before</i> the
137 * result is retrieved via {@code Future.get()}.
138 *
139 * @since 1.5
140 * @author Doug Lea
141 */
142public interface ExecutorService extends Executor {
143
144 /**
145 * Initiates an orderly shutdown in which previously submitted
146 * tasks are executed, but no new tasks will be accepted.
147 * Invocation has no additional effect if already shut down.
148 *
149 * <p>This method does not wait for previously submitted tasks to
150 * complete execution. Use {@link #awaitTermination awaitTermination}
151 * to do that.
152 */
153 void shutdown();
154
155 /**
156 * Attempts to stop all actively executing tasks, halts the
157 * processing of waiting tasks, and returns a list of the tasks
158 * that were awaiting execution.
159 *
160 * <p>This method does not wait for actively executing tasks to
161 * terminate. Use {@link #awaitTermination awaitTermination} to
162 * do that.
163 *
164 * <p>There are no guarantees beyond best-effort attempts to stop
165 * processing actively executing tasks. For example, typical
166 * implementations will cancel via {@link Thread#interrupt}, so any
167 * task that fails to respond to interrupts may never terminate.
168 *
169 * @return list of tasks that never commenced execution
170 */
171 List<Runnable> shutdownNow();
172
173 /**
174 * Returns {@code true} if this executor has been shut down.
175 *
176 * @return {@code true} if this executor has been shut down
177 */
178 boolean isShutdown();
179
180 /**
181 * Returns {@code true} if all tasks have completed following shut down.
182 * Note that {@code isTerminated} is never {@code true} unless
183 * either {@code shutdown} or {@code shutdownNow} was called first.
184 *
185 * @return {@code true} if all tasks have completed following shut down
186 */
187 boolean isTerminated();
188
189 /**
190 * Blocks until all tasks have completed execution after a shutdown
191 * request, or the timeout occurs, or the current thread is
192 * interrupted, whichever happens first.
193 *
194 * @param timeout the maximum time to wait
195 * @param unit the time unit of the timeout argument
196 * @return {@code true} if this executor terminated and
197 * {@code false} if the timeout elapsed before termination
198 * @throws InterruptedException if interrupted while waiting
199 */
200 boolean awaitTermination(long timeout, TimeUnit unit)
201 throws InterruptedException;
202
203 /**
204 * Submits a value-returning task for execution and returns a
205 * Future representing the pending results of the task. The
206 * Future's {@code get} method will return the task's result upon
207 * successful completion.
208 *
209 * <p>
210 * If you would like to immediately block waiting
211 * for a task, you can use constructions of the form
212 * {@code result = exec.submit(aCallable).get();}
213 *
214 * <p>Note: The {@link Executors} class includes a set of methods
215 * that can convert some other common closure-like objects,
216 * for example, {@link java.security.PrivilegedAction} to
217 * {@link Callable} form so they can be submitted.
218 *
219 * @param task the task to submit
220 * @param <T> the type of the task's result
221 * @return a Future representing pending completion of the task
222 * @throws RejectedExecutionException if the task cannot be
223 * scheduled for execution
224 * @throws NullPointerException if the task is null
225 */
226 <T> Future<T> submit(Callable<T> task);
227
228 /**
229 * Submits a Runnable task for execution and returns a Future
230 * representing that task. The Future's {@code get} method will
231 * return the given result upon successful completion.
232 *
233 * @param task the task to submit
234 * @param result the result to return
235 * @param <T> the type of the result
236 * @return a Future representing pending completion of the task
237 * @throws RejectedExecutionException if the task cannot be
238 * scheduled for execution
239 * @throws NullPointerException if the task is null
240 */
241 <T> Future<T> submit(Runnable task, T result);
242
243 /**
244 * Submits a Runnable task for execution and returns a Future
245 * representing that task. The Future's {@code get} method will
246 * return {@code null} upon <em>successful</em> completion.
247 *
248 * @param task the task to submit
249 * @return a Future representing pending completion of the task
250 * @throws RejectedExecutionException if the task cannot be
251 * scheduled for execution
252 * @throws NullPointerException if the task is null
253 */
254 Future<?> submit(Runnable task);
255
256 /**
257 * Executes the given tasks, returning a list of Futures holding
258 * their status and results when all complete.
259 * {@link Future#isDone} is {@code true} for each
260 * element of the returned list.
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 <T> the type of the values returned from the tasks
268 * @return a list of Futures representing the tasks, in the same
269 * sequential order as produced by the iterator for the
270 * given task list, each of which has completed
271 * @throws InterruptedException if interrupted while waiting, in
272 * which case unfinished tasks are cancelled
273 * @throws NullPointerException if tasks or any of its elements are {@code null}
274 * @throws RejectedExecutionException if any task cannot be
275 * scheduled for execution
276 */
277 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
278 throws InterruptedException;
279
280 /**
281 * Executes the given tasks, returning a list of Futures holding
282 * their status and results
283 * when all complete or the timeout expires, whichever happens first.
284 * {@link Future#isDone} is {@code true} for each
285 * element of the returned list.
286 * Upon return, tasks that have not completed are cancelled.
287 * Note that a <em>completed</em> task could have
288 * terminated either normally or by throwing an exception.
289 * The results of this method are undefined if the given
290 * collection is modified while this operation is in progress.
291 *
292 * @param tasks the collection of tasks
293 * @param timeout the maximum time to wait
294 * @param unit the time unit of the timeout argument
295 * @param <T> the type of the values returned from the tasks
296 * @return a list of Futures representing the tasks, in the same
297 * sequential order as produced by the iterator for the
298 * given task list. If the operation did not time out,
299 * each task will have completed. If it did time out, some
300 * of these tasks will not have completed.
301 * @throws InterruptedException if interrupted while waiting, in
302 * which case unfinished tasks are cancelled
303 * @throws NullPointerException if tasks, any of its elements, or
304 * unit are {@code null}
305 * @throws RejectedExecutionException if any task cannot be scheduled
306 * for execution
307 */
308 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
309 long timeout, TimeUnit unit)
310 throws InterruptedException;
311
312 /**
313 * Executes the given tasks, returning the result
314 * of one that has completed successfully (i.e., without throwing
315 * an exception), if any do. Upon normal or exceptional return,
316 * tasks that have not completed are cancelled.
317 * The results of this method are undefined if the given
318 * collection is modified while this operation is in progress.
319 *
320 * @param tasks the collection of tasks
321 * @param <T> the type of the values returned from the tasks
322 * @return the result returned by one of the tasks
323 * @throws InterruptedException if interrupted while waiting
324 * @throws NullPointerException if tasks or any element task
325 * subject to execution is {@code null}
326 * @throws IllegalArgumentException if tasks is empty
327 * @throws ExecutionException if no task successfully completes
328 * @throws RejectedExecutionException if tasks cannot be scheduled
329 * for execution
330 */
331 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
332 throws InterruptedException, ExecutionException;
333
334 /**
335 * Executes the given tasks, returning the result
336 * of one that has completed successfully (i.e., without throwing
337 * an exception), if any do before the given timeout elapses.
338 * Upon normal or exceptional return, tasks that have not
339 * completed are cancelled.
340 * The results of this method are undefined if the given
341 * collection is modified while this operation is in progress.
342 *
343 * @param tasks the collection of tasks
344 * @param timeout the maximum time to wait
345 * @param unit the time unit of the timeout argument
346 * @param <T> the type of the values returned from the tasks
347 * @return the result returned by one of the tasks
348 * @throws InterruptedException if interrupted while waiting
349 * @throws NullPointerException if tasks, or unit, or any element
350 * task subject to execution is {@code null}
351 * @throws TimeoutException if the given timeout elapses before
352 * any task successfully completes
353 * @throws ExecutionException if no task successfully completes
354 * @throws RejectedExecutionException if tasks cannot be scheduled
355 * for execution
356 */
357 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
358 long timeout, TimeUnit unit)
359 throws InterruptedException, ExecutionException, TimeoutException;
360}