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