KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > concurrent > ExecutorService


1 /*
2  * @(#)ExecutorService.java 1.6 04/07/12
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util.concurrent;
9
10 import java.util.List JavaDoc;
11 import java.util.Collection JavaDoc;
12 import java.security.PrivilegedAction JavaDoc;
13 import java.security.PrivilegedExceptionAction JavaDoc;
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>
21  * An <tt>ExecutorService</tt> can be shut down, which will cause it
22  * to stop accepting new tasks. After being shut down, the executor
23  * will eventually terminate, at which point no tasks are actively
24  * executing, no tasks are awaiting execution, and no new tasks can be
25  * submitted.
26  *
27  * <p> Method <tt>submit</tt> extends base method {@link
28  * Executor#execute} by creating and returning a {@link Future} that
29  * can be used to cancel execution and/or wait for completion.
30  * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
31  * commonly useful forms of bulk execution, executing a collection of
32  * tasks and then waiting for at least one, or all, to
33  * complete. (Class {@link ExecutorCompletionService} can be used to
34  * write customized variants of these methods.)
35  *
36  * <p>The {@link Executors} class provides factory methods for the
37  * executor services provided in this package.
38  *
39  * <h3>Usage Example</h3>
40  *
41  * Here is a sketch of a network service in which threads in a thread
42  * pool service incoming requests. It uses the preconfigured {@link
43  * Executors#newFixedThreadPool} factory method:
44  *
45  * <pre>
46  * class NetworkService {
47  * private final ServerSocket serverSocket;
48  * private final ExecutorService pool;
49  *
50  * public NetworkService(int port, int poolSize) throws IOException {
51  * serverSocket = new ServerSocket(port);
52  * pool = Executors.newFixedThreadPool(poolSize);
53  * }
54  *
55  * public void serve() {
56  * try {
57  * for (;;) {
58  * pool.execute(new Handler(serverSocket.accept()));
59  * }
60  * } catch (IOException ex) {
61  * pool.shutdown();
62  * }
63  * }
64  * }
65  *
66  * class Handler implements Runnable {
67  * private final Socket socket;
68  * Handler(Socket socket) { this.socket = socket; }
69  * public void run() {
70  * // read and service request
71  * }
72  * }
73  * </pre>
74  * @since 1.5
75  * @author Doug Lea
76  */

77 public interface ExecutorService extends Executor JavaDoc {
78
79     /**
80      * Initiates an orderly shutdown in which previously submitted
81      * tasks are executed, but no new tasks will be
82      * accepted. Invocation has no additional effect if already shut
83      * down.
84      * @throws SecurityException if a security manager exists and
85      * shutting down this ExecutorService may manipulate threads that
86      * the caller is not permitted to modify because it does not hold
87      * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
88      * or the security manager's <tt>checkAccess</tt> method denies access.
89      */

90     void shutdown();
91
92     /**
93      * Attempts to stop all actively executing tasks, halts the
94      * processing of waiting tasks, and returns a list of the tasks that were
95      * awaiting execution.
96      *
97      * <p>There are no guarantees beyond best-effort attempts to stop
98      * processing actively executing tasks. For example, typical
99      * implementations will cancel via {@link Thread#interrupt}, so if any
100      * tasks mask or fail to respond to interrupts, they may never terminate.
101      *
102      * @return list of tasks that never commenced execution
103      * @throws SecurityException if a security manager exists and
104      * shutting down this ExecutorService may manipulate threads that
105      * the caller is not permitted to modify because it does not hold
106      * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
107      * or the security manager's <tt>checkAccess</tt> method denies access.
108      */

109     List JavaDoc<Runnable JavaDoc> shutdownNow();
110
111     /**
112      * Returns <tt>true</tt> if this executor has been shut down.
113      *
114      * @return <tt>true</tt> if this executor has been shut down
115      */

116     boolean isShutdown();
117
118     /**
119      * Returns <tt>true</tt> if all tasks have completed following shut down.
120      * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
121      * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
122      *
123      * @return <tt>true</tt> if all tasks have completed following shut down
124      */

125     boolean isTerminated();
126
127     /**
128      * Blocks until all tasks have completed execution after a shutdown
129      * request, or the timeout occurs, or the current thread is
130      * interrupted, whichever happens first.
131      *
132      * @param timeout the maximum time to wait
133      * @param unit the time unit of the timeout argument
134      * @return <tt>true</tt> if this executor terminated and <tt>false</tt>
135      * if the timeout elapsed before termination
136      * @throws InterruptedException if interrupted while waiting
137      */

138     boolean awaitTermination(long timeout, TimeUnit JavaDoc unit)
139         throws InterruptedException JavaDoc;
140
141
142     /**
143      * Submits a value-returning task for execution and returns a Future
144      * representing the pending results of the task.
145      *
146      * <p>
147      * If you would like to immediately block waiting
148      * for a task, you can use constructions of the form
149      * <tt>result = exec.submit(aCallable).get();</tt>
150      *
151      * <p> Note: The {@link Executors} class includes a set of methods
152      * that can convert some other common closure-like objects,
153      * for example, {@link java.security.PrivilegedAction} to
154      * {@link Callable} form so they can be submitted.
155      *
156      * @param task the task to submit
157      * @return a Future representing pending completion of the task
158      * @throws RejectedExecutionException if task cannot be scheduled
159      * for execution
160      * @throws NullPointerException if task null
161      */

162     <T> Future JavaDoc<T> submit(Callable JavaDoc<T> task);
163
164     /**
165      * Submits a Runnable task for execution and returns a Future
166      * representing that task that will upon completion return
167      * the given result
168      *
169      * @param task the task to submit
170      * @param result the result to return
171      * @return a Future representing pending completion of the task,
172      * and whose <tt>get()</tt> method will return the given result
173      * upon completion.
174      * @throws RejectedExecutionException if task cannot be scheduled
175      * for execution
176      * @throws NullPointerException if task null
177      */

178     <T> Future JavaDoc<T> submit(Runnable JavaDoc task, T result);
179
180     /**
181      * Submits a Runnable task for execution and returns a Future
182      * representing that task.
183      *
184      * @param task the task to submit
185      * @return a Future representing pending completion of the task,
186      * and whose <tt>get()</tt> method will return <tt>null</tt>
187      * upon completion.
188      * @throws RejectedExecutionException if task cannot be scheduled
189      * for execution
190      * @throws NullPointerException if task null
191      */

192     Future JavaDoc<?> submit(Runnable JavaDoc task);
193
194     /**
195      * Executes the given tasks, returning a list of Futures holding
196      * their status and results when all complete.
197      * {@link Future#isDone} is <tt>true</tt> for each
198      * element of the returned list.
199      * Note that a <em>completed</em> task could have
200      * terminated either normally or by throwing an exception.
201      * The results of this method are undefined if the given
202      * collection is modified while this operation is in progress.
203      * @param tasks the collection of tasks
204      * @return A list of Futures representing the tasks, in the same
205      * sequential order as produced by the iterator for the given task
206      * list, each of which has completed.
207      * @throws InterruptedException if interrupted while waiting, in
208      * which case unfinished tasks are cancelled.
209      * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
210      * @throws RejectedExecutionException if any task cannot be scheduled
211      * for execution
212      */

213
214     <T> List JavaDoc<Future JavaDoc<T>> invokeAll(Collection JavaDoc<Callable JavaDoc<T>> tasks)
215         throws InterruptedException JavaDoc;
216
217     /**
218      * Executes the given tasks, returning a list of Futures holding
219      * their status and results
220      * when all complete or the timeout expires, whichever happens first.
221      * {@link Future#isDone} is <tt>true</tt> for each
222      * element of the returned list.
223      * Upon return, tasks that have not completed are cancelled.
224      * Note that a <em>completed</em> task could have
225      * terminated either normally or by throwing an exception.
226      * The results of this method are undefined if the given
227      * collection is modified while this operation is in progress.
228      * @param tasks the collection of tasks
229      * @param timeout the maximum time to wait
230      * @param unit the time unit of the timeout argument
231      * @return A list of Futures representing the tasks, in the same
232      * sequential order as produced by the iterator for the given
233      * task list. If the operation did not time out, each task will
234      * have completed. If it did time out, some of these tasks will
235      * not have completed.
236      * @throws InterruptedException if interrupted while waiting, in
237      * which case unfinished tasks are cancelled.
238      * @throws NullPointerException if tasks, any of its elements, or
239      * unit are <tt>null</tt>
240      * @throws RejectedExecutionException if any task cannot be scheduled
241      * for execution
242      */

243     <T> List JavaDoc<Future JavaDoc<T>> invokeAll(Collection JavaDoc<Callable JavaDoc<T>> tasks,
244                                   long timeout, TimeUnit JavaDoc unit)
245         throws InterruptedException JavaDoc;
246
247     /**
248      * Executes the given tasks, returning the result
249      * of one that has completed successfully (i.e., without throwing
250      * an exception), if any do. Upon normal or exceptional return,
251      * tasks that have not completed are cancelled.
252      * The results of this method are undefined if the given
253      * collection is modified while this operation is in progress.
254      * @param tasks the collection of tasks
255      * @return The result returned by one of the tasks.
256      * @throws InterruptedException if interrupted while waiting
257      * @throws NullPointerException if tasks or any of its elements
258      * are <tt>null</tt>
259      * @throws IllegalArgumentException if tasks empty
260      * @throws ExecutionException if no task successfully completes
261      * @throws RejectedExecutionException if tasks cannot be scheduled
262      * for execution
263      */

264     <T> T invokeAny(Collection JavaDoc<Callable JavaDoc<T>> tasks)
265         throws InterruptedException JavaDoc, ExecutionException JavaDoc;
266
267     /**
268      * Executes the given tasks, returning the result
269      * of one that has completed successfully (i.e., without throwing
270      * an exception), if any do before the given timeout elapses.
271      * Upon normal or exceptional return, tasks that have not
272      * completed are cancelled.
273      * The results of this method are undefined if the given
274      * collection is modified while this operation is in progress.
275      * @param tasks the collection of tasks
276      * @param timeout the maximum time to wait
277      * @param unit the time unit of the timeout argument
278      * @return The result returned by one of the tasks.
279      * @throws InterruptedException if interrupted while waiting
280      * @throws NullPointerException if tasks, any of its elements, or
281      * unit are <tt>null</tt>
282      * @throws TimeoutException if the given timeout elapses before
283      * any task successfully completes
284      * @throws ExecutionException if no task successfully completes
285      * @throws RejectedExecutionException if tasks cannot be scheduled
286      * for execution
287      */

288     <T> T invokeAny(Collection JavaDoc<Callable JavaDoc<T>> tasks,
289                     long timeout, TimeUnit JavaDoc unit)
290         throws InterruptedException JavaDoc, ExecutionException JavaDoc, TimeoutException JavaDoc;
291
292 }
293
Popular Tags