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. package java.util.concurrent;
  8. import java.util.List;
  9. import java.util.Collection;
  10. import java.security.PrivilegedAction;
  11. import java.security.PrivilegedExceptionAction;
  12. /**
  13. * An {@link Executor} that provides methods to manage termination and
  14. * methods that can produce a {@link Future} for tracking progress of
  15. * one or more asynchronous tasks.
  16. *
  17. * <p>
  18. * An <tt>ExecutorService</tt> can be shut down, which will cause it
  19. * to stop accepting new tasks. After being shut down, the executor
  20. * will eventually terminate, at which point no tasks are actively
  21. * executing, no tasks are awaiting execution, and no new tasks can be
  22. * submitted.
  23. *
  24. * <p> Method <tt>submit</tt> extends base method {@link
  25. * Executor#execute} by creating and returning a {@link Future} that
  26. * can be used to cancel execution and/or wait for completion.
  27. * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
  28. * commonly useful forms of bulk execution, executing a collection of
  29. * tasks and then waiting for at least one, or all, to
  30. * complete. (Class {@link ExecutorCompletionService} can be used to
  31. * write customized variants of these methods.)
  32. *
  33. * <p>The {@link Executors} class provides factory methods for the
  34. * executor services provided in this package.
  35. *
  36. * <h3>Usage Example</h3>
  37. *
  38. * Here is a sketch of a network service in which threads in a thread
  39. * pool service incoming requests. It uses the preconfigured {@link
  40. * Executors#newFixedThreadPool} factory method:
  41. *
  42. * <pre>
  43. * class NetworkService {
  44. * private final ServerSocket serverSocket;
  45. * private final ExecutorService pool;
  46. *
  47. * public NetworkService(int port, int poolSize) throws IOException {
  48. * serverSocket = new ServerSocket(port);
  49. * pool = Executors.newFixedThreadPool(poolSize);
  50. * }
  51. *
  52. * public void serve() {
  53. * try {
  54. * for (;;) {
  55. * pool.execute(new Handler(serverSocket.accept()));
  56. * }
  57. * } catch (IOException ex) {
  58. * pool.shutdown();
  59. * }
  60. * }
  61. * }
  62. *
  63. * class Handler implements Runnable {
  64. * private final Socket socket;
  65. * Handler(Socket socket) { this.socket = socket; }
  66. * public void run() {
  67. * // read and service request
  68. * }
  69. * }
  70. * </pre>
  71. * @since 1.5
  72. * @author Doug Lea
  73. */
  74. public interface ExecutorService extends Executor {
  75. /**
  76. * Initiates an orderly shutdown in which previously submitted
  77. * tasks are executed, but no new tasks will be
  78. * accepted. Invocation has no additional effect if already shut
  79. * down.
  80. * @throws SecurityException if a security manager exists and
  81. * shutting down this ExecutorService may manipulate threads that
  82. * the caller is not permitted to modify because it does not hold
  83. * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
  84. * or the security manager's <tt>checkAccess</tt> method denies access.
  85. */
  86. void shutdown();
  87. /**
  88. * Attempts to stop all actively executing tasks, halts the
  89. * processing of waiting tasks, and returns a list of the tasks that were
  90. * awaiting execution.
  91. *
  92. * <p>There are no guarantees beyond best-effort attempts to stop
  93. * processing actively executing tasks. For example, typical
  94. * implementations will cancel via {@link Thread#interrupt}, so if any
  95. * tasks mask or fail to respond to interrupts, they may never terminate.
  96. *
  97. * @return list of tasks that never commenced execution
  98. * @throws SecurityException if a security manager exists and
  99. * shutting down this ExecutorService may manipulate threads that
  100. * the caller is not permitted to modify because it does not hold
  101. * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
  102. * or the security manager's <tt>checkAccess</tt> method denies access.
  103. */
  104. List<Runnable> shutdownNow();
  105. /**
  106. * Returns <tt>true</tt> if this executor has been shut down.
  107. *
  108. * @return <tt>true</tt> if this executor has been shut down
  109. */
  110. boolean isShutdown();
  111. /**
  112. * Returns <tt>true</tt> if all tasks have completed following shut down.
  113. * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
  114. * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
  115. *
  116. * @return <tt>true</tt> if all tasks have completed following shut down
  117. */
  118. boolean isTerminated();
  119. /**
  120. * Blocks until all tasks have completed execution after a shutdown
  121. * request, or the timeout occurs, or the current thread is
  122. * interrupted, whichever happens first.
  123. *
  124. * @param timeout the maximum time to wait
  125. * @param unit the time unit of the timeout argument
  126. * @return <tt>true</tt> if this executor terminated and <tt>false</tt>
  127. * if the timeout elapsed before termination
  128. * @throws InterruptedException if interrupted while waiting
  129. */
  130. boolean awaitTermination(long timeout, TimeUnit unit)
  131. throws InterruptedException;
  132. /**
  133. * Submits a value-returning task for execution and returns a Future
  134. * representing the pending results of the task.
  135. *
  136. * <p>
  137. * If you would like to immediately block waiting
  138. * for a task, you can use constructions of the form
  139. * <tt>result = exec.submit(aCallable).get();</tt>
  140. *
  141. * <p> Note: The {@link Executors} class includes a set of methods
  142. * that can convert some other common closure-like objects,
  143. * for example, {@link java.security.PrivilegedAction} to
  144. * {@link Callable} form so they can be submitted.
  145. *
  146. * @param task the task to submit
  147. * @return a Future representing pending completion of the task
  148. * @throws RejectedExecutionException if task cannot be scheduled
  149. * for execution
  150. * @throws NullPointerException if task null
  151. */
  152. <T> Future<T> submit(Callable<T> task);
  153. /**
  154. * Submits a Runnable task for execution and returns a Future
  155. * representing that task that will upon completion return
  156. * the given result
  157. *
  158. * @param task the task to submit
  159. * @param result the result to return
  160. * @return a Future representing pending completion of the task,
  161. * and whose <tt>get()</tt> method will return the given result
  162. * upon completion.
  163. * @throws RejectedExecutionException if task cannot be scheduled
  164. * for execution
  165. * @throws NullPointerException if task null
  166. */
  167. <T> Future<T> submit(Runnable task, T result);
  168. /**
  169. * Submits a Runnable task for execution and returns a Future
  170. * representing that task.
  171. *
  172. * @param task the task to submit
  173. * @return a Future representing pending completion of the task,
  174. * and whose <tt>get()</tt> method will return <tt>null</tt>
  175. * upon completion.
  176. * @throws RejectedExecutionException if task cannot be scheduled
  177. * for execution
  178. * @throws NullPointerException if task null
  179. */
  180. Future<?> submit(Runnable task);
  181. /**
  182. * Executes the given tasks, returning a list of Futures holding
  183. * their status and results when all complete.
  184. * {@link Future#isDone} is <tt>true</tt> for each
  185. * element of the returned list.
  186. * Note that a <em>completed</em> task could have
  187. * terminated either normally or by throwing an exception.
  188. * The results of this method are undefined if the given
  189. * collection is modified while this operation is in progress.
  190. * @param tasks the collection of tasks
  191. * @return A list of Futures representing the tasks, in the same
  192. * sequential order as produced by the iterator for the given task
  193. * list, each of which has completed.
  194. * @throws InterruptedException if interrupted while waiting, in
  195. * which case unfinished tasks are cancelled.
  196. * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
  197. * @throws RejectedExecutionException if any task cannot be scheduled
  198. * for execution
  199. */
  200. <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
  201. throws InterruptedException;
  202. /**
  203. * Executes the given tasks, returning a list of Futures holding
  204. * their status and results
  205. * when all complete or the timeout expires, whichever happens first.
  206. * {@link Future#isDone} is <tt>true</tt> for each
  207. * element of the returned list.
  208. * Upon return, tasks that have not completed are cancelled.
  209. * Note that a <em>completed</em> task could have
  210. * terminated either normally or by throwing an exception.
  211. * The results of this method are undefined if the given
  212. * collection is modified while this operation is in progress.
  213. * @param tasks the collection of tasks
  214. * @param timeout the maximum time to wait
  215. * @param unit the time unit of the timeout argument
  216. * @return A list of Futures representing the tasks, in the same
  217. * sequential order as produced by the iterator for the given
  218. * task list. If the operation did not time out, each task will
  219. * have completed. If it did time out, some of these tasks will
  220. * not have completed.
  221. * @throws InterruptedException if interrupted while waiting, in
  222. * which case unfinished tasks are cancelled.
  223. * @throws NullPointerException if tasks, any of its elements, or
  224. * unit are <tt>null</tt>
  225. * @throws RejectedExecutionException if any task cannot be scheduled
  226. * for execution
  227. */
  228. <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks,
  229. long timeout, TimeUnit unit)
  230. throws InterruptedException;
  231. /**
  232. * Executes the given tasks, returning the result
  233. * of one that has completed successfully (i.e., without throwing
  234. * an exception), if any do. Upon normal or exceptional return,
  235. * tasks that have not completed are cancelled.
  236. * The results of this method are undefined if the given
  237. * collection is modified while this operation is in progress.
  238. * @param tasks the collection of tasks
  239. * @return The result returned by one of the tasks.
  240. * @throws InterruptedException if interrupted while waiting
  241. * @throws NullPointerException if tasks or any of its elements
  242. * are <tt>null</tt>
  243. * @throws IllegalArgumentException if tasks empty
  244. * @throws ExecutionException if no task successfully completes
  245. * @throws RejectedExecutionException if tasks cannot be scheduled
  246. * for execution
  247. */
  248. <T> T invokeAny(Collection<Callable<T>> tasks)
  249. throws InterruptedException, ExecutionException;
  250. /**
  251. * Executes the given tasks, returning the result
  252. * of one that has completed successfully (i.e., without throwing
  253. * an exception), if any do before the given timeout elapses.
  254. * Upon normal or exceptional return, tasks that have not
  255. * completed are cancelled.
  256. * The results of this method are undefined if the given
  257. * collection is modified while this operation is in progress.
  258. * @param tasks the collection of tasks
  259. * @param timeout the maximum time to wait
  260. * @param unit the time unit of the timeout argument
  261. * @return The result returned by one of the tasks.
  262. * @throws InterruptedException if interrupted while waiting
  263. * @throws NullPointerException if tasks, any of its elements, or
  264. * unit are <tt>null</tt>
  265. * @throws TimeoutException if the given timeout elapses before
  266. * any task successfully completes
  267. * @throws ExecutionException if no task successfully completes
  268. * @throws RejectedExecutionException if tasks cannot be scheduled
  269. * for execution
  270. */
  271. <T> T invokeAny(Collection<Callable<T>> tasks,
  272. long timeout, TimeUnit unit)
  273. throws InterruptedException, ExecutionException, TimeoutException;
  274. }