001 /*
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
003 *
004 * This code is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU General Public License version 2 only, as
006 * published by the Free Software Foundation. Sun designates this
007 * particular file as subject to the "Classpath" exception as provided
008 * by Sun in the LICENSE file that accompanied this code.
009 *
010 * This code is distributed in the hope that it will be useful, but WITHOUT
011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
013 * version 2 for more details (a copy is included in the LICENSE file that
014 * accompanied this code).
015 *
016 * You should have received a copy of the GNU General Public License version
017 * 2 along with this work; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
019 *
020 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
021 * CA 95054 USA or visit www.sun.com if you need additional information or
022 * have any questions.
023 */
024
025 /*
026 * This file is available under and governed by the GNU General Public
027 * License version 2 only, as published by the Free Software Foundation.
028 * However, the following notice accompanied the original version of this
029 * file:
030 *
031 * Written by Doug Lea with assistance from members of JCP JSR-166
032 * Expert Group and released to the public domain, as explained at
033 * http://creativecommons.org/licenses/publicdomain
034 */
035
036 package java.util.concurrent;
037
038 import java.util.List;
039 import java.util.Collection;
040 import java.security.PrivilegedAction;
041 import java.security.PrivilegedExceptionAction;
042
043 /**
044 * An {@link Executor} that provides methods to manage termination and
045 * methods that can produce a {@link Future} for tracking progress of
046 * one or more asynchronous tasks.
047 *
048 * <p> An <tt>ExecutorService</tt> can be shut down, which will cause
049 * it to reject new tasks. Two different methods are provided for
050 * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown}
051 * method will allow previously submitted tasks to execute before
052 * terminating, while the {@link #shutdownNow} method prevents waiting
053 * tasks from starting and attempts to stop currently executing tasks.
054 * Upon termination, an executor has no tasks actively executing, no
055 * tasks awaiting execution, and no new tasks can be submitted. An
056 * unused <tt>ExecutorService</tt> should be shut down to allow
057 * reclamation of its resources.
058 *
059 * <p> Method <tt>submit</tt> extends base method {@link
060 * Executor#execute} by creating and returning a {@link Future} that
061 * can be used to cancel execution and/or wait for completion.
062 * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
063 * commonly useful forms of bulk execution, executing a collection of
064 * tasks and then waiting for at least one, or all, to
065 * complete. (Class {@link ExecutorCompletionService} can be used to
066 * write customized variants of these methods.)
067 *
068 * <p>The {@link Executors} class provides factory methods for the
069 * executor services provided in this package.
070 *
071 * <h3>Usage Examples</h3>
072 *
073 * Here is a sketch of a network service in which threads in a thread
074 * pool service incoming requests. It uses the preconfigured {@link
075 * Executors#newFixedThreadPool} factory method:
076 *
077 * <pre>
078 * class NetworkService implements Runnable {
079 * private final ServerSocket serverSocket;
080 * private final ExecutorService pool;
081 *
082 * public NetworkService(int port, int poolSize)
083 * throws IOException {
084 * serverSocket = new ServerSocket(port);
085 * pool = Executors.newFixedThreadPool(poolSize);
086 * }
087 *
088 * public void run() { // run the service
089 * try {
090 * for (;;) {
091 * pool.execute(new Handler(serverSocket.accept()));
092 * }
093 * } catch (IOException ex) {
094 * pool.shutdown();
095 * }
096 * }
097 * }
098 *
099 * class Handler implements Runnable {
100 * private final Socket socket;
101 * Handler(Socket socket) { this.socket = socket; }
102 * public void run() {
103 * // read and service request on socket
104 * }
105 * }
106 * </pre>
107 *
108 * The following method shuts down an <tt>ExecutorService</tt> in two phases,
109 * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
110 * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
111 *
112 * <pre>
113 * void shutdownAndAwaitTermination(ExecutorService pool) {
114 * pool.shutdown(); // Disable new tasks from being submitted
115 * try {
116 * // Wait a while for existing tasks to terminate
117 * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
118 * pool.shutdownNow(); // Cancel currently executing tasks
119 * // Wait a while for tasks to respond to being cancelled
120 * if (!pool.awaitTermination(60, TimeUnit.SECONDS))
121 * System.err.println("Pool did not terminate");
122 * }
123 * } catch (InterruptedException ie) {
124 * // (Re-)Cancel if current thread also interrupted
125 * pool.shutdownNow();
126 * // Preserve interrupt status
127 * Thread.currentThread().interrupt();
128 * }
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 */
142 public 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 * @throws SecurityException if a security manager exists and
150 * shutting down this ExecutorService may manipulate
151 * threads that the caller is not permitted to modify
152 * because it does not hold {@link
153 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
154 * or the security manager's <tt>checkAccess</tt> method
155 * denies access.
156 */
157 void shutdown();
158
159 /**
160 * Attempts to stop all actively executing tasks, halts the
161 * processing of waiting tasks, and returns a list of the tasks that were
162 * awaiting execution.
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 * @throws SecurityException if a security manager exists and
171 * shutting down this ExecutorService may manipulate
172 * threads that the caller is not permitted to modify
173 * because it does not hold {@link
174 * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
175 * or the security manager's <tt>checkAccess</tt> method
176 * denies access.
177 */
178 List<Runnable> shutdownNow();
179
180 /**
181 * Returns <tt>true</tt> if this executor has been shut down.
182 *
183 * @return <tt>true</tt> if this executor has been shut down
184 */
185 boolean isShutdown();
186
187 /**
188 * Returns <tt>true</tt> if all tasks have completed following shut down.
189 * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
190 * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
191 *
192 * @return <tt>true</tt> if all tasks have completed following shut down
193 */
194 boolean isTerminated();
195
196 /**
197 * Blocks until all tasks have completed execution after a shutdown
198 * request, or the timeout occurs, or the current thread is
199 * interrupted, whichever happens first.
200 *
201 * @param timeout the maximum time to wait
202 * @param unit the time unit of the timeout argument
203 * @return <tt>true</tt> if this executor terminated and
204 * <tt>false</tt> if the timeout elapsed before termination
205 * @throws InterruptedException if interrupted while waiting
206 */
207 boolean awaitTermination(long timeout, TimeUnit unit)
208 throws InterruptedException;
209
210 /**
211 * Submits a value-returning task for execution and returns a
212 * Future representing the pending results of the task. The
213 * Future's <tt>get</tt> method will return the task's result upon
214 * successful completion.
215 *
216 * <p>
217 * If you would like to immediately block waiting
218 * for a task, you can use constructions of the form
219 * <tt>result = exec.submit(aCallable).get();</tt>
220 *
221 * <p> Note: The {@link Executors} class includes a set of methods
222 * that can convert some other common closure-like objects,
223 * for example, {@link java.security.PrivilegedAction} to
224 * {@link Callable} form so they can be submitted.
225 *
226 * @param task the task to submit
227 * @return a Future representing pending completion of the task
228 * @throws RejectedExecutionException if the task cannot be
229 * scheduled for execution
230 * @throws NullPointerException if the task is null
231 */
232 <T> Future<T> submit(Callable<T> task);
233
234 /**
235 * Submits a Runnable task for execution and returns a Future
236 * representing that task. The Future's <tt>get</tt> method will
237 * return the given result upon successful completion.
238 *
239 * @param task the task to submit
240 * @param result the result to return
241 * @return a Future representing pending completion of the task
242 * @throws RejectedExecutionException if the task cannot be
243 * scheduled for execution
244 * @throws NullPointerException if the task is null
245 */
246 <T> Future<T> submit(Runnable task, T result);
247
248 /**
249 * Submits a Runnable task for execution and returns a Future
250 * representing that task. The Future's <tt>get</tt> method will
251 * return <tt>null</tt> upon <em>successful</em> completion.
252 *
253 * @param task the task to submit
254 * @return a Future representing pending completion of the task
255 * @throws RejectedExecutionException if the task cannot be
256 * scheduled for execution
257 * @throws NullPointerException if the task is null
258 */
259 Future<?> submit(Runnable task);
260
261 /**
262 * Executes the given tasks, returning a list of Futures holding
263 * their status and results when all complete.
264 * {@link Future#isDone} is <tt>true</tt> for each
265 * element of the returned list.
266 * Note that a <em>completed</em> task could have
267 * terminated either normally or by throwing an exception.
268 * The results of this method are undefined if the given
269 * collection is modified while this operation is in progress.
270 *
271 * @param tasks the collection of tasks
272 * @return A list of Futures representing the tasks, in the same
273 * sequential order as produced by the iterator for the
274 * given task list, each of which has completed.
275 * @throws InterruptedException if interrupted while waiting, in
276 * which case unfinished tasks are cancelled.
277 * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
278 * @throws RejectedExecutionException if any task cannot be
279 * scheduled for execution
280 */
281
282 <T> List<Future<T>> invokeAll(
283 Collection<? extends Callable<T>> tasks)
284 throws InterruptedException;
285
286 /**
287 * Executes the given tasks, returning a list of Futures holding
288 * their status and results
289 * when all complete or the timeout expires, whichever happens first.
290 * {@link Future#isDone} is <tt>true</tt> for each
291 * element of the returned list.
292 * Upon return, tasks that have not completed are cancelled.
293 * Note that a <em>completed</em> task could have
294 * terminated either normally or by throwing an exception.
295 * The results of this method are undefined if the given
296 * collection is modified while this operation is in progress.
297 *
298 * @param tasks the collection of tasks
299 * @param timeout the maximum time to wait
300 * @param unit the time unit of the timeout argument
301 * @return a list of Futures representing the tasks, in the same
302 * sequential order as produced by the iterator for the
303 * given task list. If the operation did not time out,
304 * each task will have completed. If it did time out, some
305 * of these tasks will not have completed.
306 * @throws InterruptedException if interrupted while waiting, in
307 * which case unfinished tasks are cancelled
308 * @throws NullPointerException if tasks, any of its elements, or
309 * unit are <tt>null</tt>
310 * @throws RejectedExecutionException if any task cannot be scheduled
311 * for execution
312 */
313 <T> List<Future<T>> invokeAll(
314 Collection<? extends Callable<T>> tasks, long timeout,
315 TimeUnit unit) throws InterruptedException;
316
317 /**
318 * Executes the given tasks, returning the result
319 * of one that has completed successfully (i.e., without throwing
320 * an exception), if any do. Upon normal or exceptional return,
321 * tasks that have not completed are cancelled.
322 * The results of this method are undefined if the given
323 * collection is modified while this operation is in progress.
324 *
325 * @param tasks the collection of tasks
326 * @return the result returned by one of the tasks
327 * @throws InterruptedException if interrupted while waiting
328 * @throws NullPointerException if tasks or any of its elements
329 * are <tt>null</tt>
330 * @throws IllegalArgumentException if tasks is empty
331 * @throws ExecutionException if no task successfully completes
332 * @throws RejectedExecutionException if tasks cannot be scheduled
333 * for execution
334 */
335 <T> T invokeAny(Collection<? extends Callable<T>> tasks)
336 throws InterruptedException, ExecutionException;
337
338 /**
339 * Executes the given tasks, returning the result
340 * of one that has completed successfully (i.e., without throwing
341 * an exception), if any do before the given timeout elapses.
342 * Upon normal or exceptional return, tasks that have not
343 * completed are cancelled.
344 * The results of this method are undefined if the given
345 * collection is modified while this operation is in progress.
346 *
347 * @param tasks the collection of tasks
348 * @param timeout the maximum time to wait
349 * @param unit the time unit of the timeout argument
350 * @return the result returned by one of the tasks.
351 * @throws InterruptedException if interrupted while waiting
352 * @throws NullPointerException if tasks, any of its elements, or
353 * unit are <tt>null</tt>
354 * @throws TimeoutException if the given timeout elapses before
355 * any task successfully completes
356 * @throws ExecutionException if no task successfully completes
357 * @throws RejectedExecutionException if tasks cannot be scheduled
358 * for execution
359 */
360 <T> T invokeAny(Collection<? extends Callable<T>> tasks,
361 long timeout, TimeUnit unit) throws InterruptedException,
362 ExecutionException, TimeoutException;
363 }
|