rt/emul/compact/src/main/java/java/util/concurrent/ExecutorService.java
branchjdk7-b147
changeset 1890 212417b74b72
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/util/concurrent/ExecutorService.java	Sat Mar 19 10:46:31 2016 +0100
     1.3 @@ -0,0 +1,370 @@
     1.4 +/*
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.6 + *
     1.7 + * This code is free software; you can redistribute it and/or modify it
     1.8 + * under the terms of the GNU General Public License version 2 only, as
     1.9 + * published by the Free Software Foundation.  Oracle designates this
    1.10 + * particular file as subject to the "Classpath" exception as provided
    1.11 + * by Oracle in the LICENSE file that accompanied this code.
    1.12 + *
    1.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.15 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.16 + * version 2 for more details (a copy is included in the LICENSE file that
    1.17 + * accompanied this code).
    1.18 + *
    1.19 + * You should have received a copy of the GNU General Public License version
    1.20 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.22 + *
    1.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.24 + * or visit www.oracle.com if you need additional information or have any
    1.25 + * questions.
    1.26 + */
    1.27 +
    1.28 +/*
    1.29 + * This file is available under and governed by the GNU General Public
    1.30 + * License version 2 only, as published by the Free Software Foundation.
    1.31 + * However, the following notice accompanied the original version of this
    1.32 + * file:
    1.33 + *
    1.34 + * Written by Doug Lea with assistance from members of JCP JSR-166
    1.35 + * Expert Group and released to the public domain, as explained at
    1.36 + * http://creativecommons.org/publicdomain/zero/1.0/
    1.37 + */
    1.38 +
    1.39 +package java.util.concurrent;
    1.40 +import java.util.List;
    1.41 +import java.util.Collection;
    1.42 +import java.security.PrivilegedAction;
    1.43 +import java.security.PrivilegedExceptionAction;
    1.44 +
    1.45 +/**
    1.46 + * An {@link Executor} that provides methods to manage termination and
    1.47 + * methods that can produce a {@link Future} for tracking progress of
    1.48 + * one or more asynchronous tasks.
    1.49 + *
    1.50 + * <p> An <tt>ExecutorService</tt> can be shut down, which will cause
    1.51 + * it to reject new tasks.  Two different methods are provided for
    1.52 + * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown}
    1.53 + * method will allow previously submitted tasks to execute before
    1.54 + * terminating, while the {@link #shutdownNow} method prevents waiting
    1.55 + * tasks from starting and attempts to stop currently executing tasks.
    1.56 + * Upon termination, an executor has no tasks actively executing, no
    1.57 + * tasks awaiting execution, and no new tasks can be submitted.  An
    1.58 + * unused <tt>ExecutorService</tt> should be shut down to allow
    1.59 + * reclamation of its resources.
    1.60 + *
    1.61 + * <p> Method <tt>submit</tt> extends base method {@link
    1.62 + * Executor#execute} by creating and returning a {@link Future} that
    1.63 + * can be used to cancel execution and/or wait for completion.
    1.64 + * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
    1.65 + * commonly useful forms of bulk execution, executing a collection of
    1.66 + * tasks and then waiting for at least one, or all, to
    1.67 + * complete. (Class {@link ExecutorCompletionService} can be used to
    1.68 + * write customized variants of these methods.)
    1.69 + *
    1.70 + * <p>The {@link Executors} class provides factory methods for the
    1.71 + * executor services provided in this package.
    1.72 + *
    1.73 + * <h3>Usage Examples</h3>
    1.74 + *
    1.75 + * Here is a sketch of a network service in which threads in a thread
    1.76 + * pool service incoming requests. It uses the preconfigured {@link
    1.77 + * Executors#newFixedThreadPool} factory method:
    1.78 + *
    1.79 + * <pre>
    1.80 + * class NetworkService implements Runnable {
    1.81 + *   private final ServerSocket serverSocket;
    1.82 + *   private final ExecutorService pool;
    1.83 + *
    1.84 + *   public NetworkService(int port, int poolSize)
    1.85 + *       throws IOException {
    1.86 + *     serverSocket = new ServerSocket(port);
    1.87 + *     pool = Executors.newFixedThreadPool(poolSize);
    1.88 + *   }
    1.89 + *
    1.90 + *   public void run() { // run the service
    1.91 + *     try {
    1.92 + *       for (;;) {
    1.93 + *         pool.execute(new Handler(serverSocket.accept()));
    1.94 + *       }
    1.95 + *     } catch (IOException ex) {
    1.96 + *       pool.shutdown();
    1.97 + *     }
    1.98 + *   }
    1.99 + * }
   1.100 + *
   1.101 + * class Handler implements Runnable {
   1.102 + *   private final Socket socket;
   1.103 + *   Handler(Socket socket) { this.socket = socket; }
   1.104 + *   public void run() {
   1.105 + *     // read and service request on socket
   1.106 + *   }
   1.107 + * }
   1.108 + * </pre>
   1.109 + *
   1.110 + * The following method shuts down an <tt>ExecutorService</tt> in two phases,
   1.111 + * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
   1.112 + * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
   1.113 + *
   1.114 + * <pre>
   1.115 + * void shutdownAndAwaitTermination(ExecutorService pool) {
   1.116 + *   pool.shutdown(); // Disable new tasks from being submitted
   1.117 + *   try {
   1.118 + *     // Wait a while for existing tasks to terminate
   1.119 + *     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
   1.120 + *       pool.shutdownNow(); // Cancel currently executing tasks
   1.121 + *       // Wait a while for tasks to respond to being cancelled
   1.122 + *       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
   1.123 + *           System.err.println("Pool did not terminate");
   1.124 + *     }
   1.125 + *   } catch (InterruptedException ie) {
   1.126 + *     // (Re-)Cancel if current thread also interrupted
   1.127 + *     pool.shutdownNow();
   1.128 + *     // Preserve interrupt status
   1.129 + *     Thread.currentThread().interrupt();
   1.130 + *   }
   1.131 + * }
   1.132 + * </pre>
   1.133 + *
   1.134 + * <p>Memory consistency effects: Actions in a thread prior to the
   1.135 + * submission of a {@code Runnable} or {@code Callable} task to an
   1.136 + * {@code ExecutorService}
   1.137 + * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
   1.138 + * any actions taken by that task, which in turn <i>happen-before</i> the
   1.139 + * result is retrieved via {@code Future.get()}.
   1.140 + *
   1.141 + * @since 1.5
   1.142 + * @author Doug Lea
   1.143 + */
   1.144 +public interface ExecutorService extends Executor {
   1.145 +
   1.146 +    /**
   1.147 +     * Initiates an orderly shutdown in which previously submitted
   1.148 +     * tasks are executed, but no new tasks will be accepted.
   1.149 +     * Invocation has no additional effect if already shut down.
   1.150 +     *
   1.151 +     * <p>This method does not wait for previously submitted tasks to
   1.152 +     * complete execution.  Use {@link #awaitTermination awaitTermination}
   1.153 +     * to do that.
   1.154 +     *
   1.155 +     * @throws SecurityException if a security manager exists and
   1.156 +     *         shutting down this ExecutorService may manipulate
   1.157 +     *         threads that the caller is not permitted to modify
   1.158 +     *         because it does not hold {@link
   1.159 +     *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
   1.160 +     *         or the security manager's <tt>checkAccess</tt> method
   1.161 +     *         denies access.
   1.162 +     */
   1.163 +    void shutdown();
   1.164 +
   1.165 +    /**
   1.166 +     * Attempts to stop all actively executing tasks, halts the
   1.167 +     * processing of waiting tasks, and returns a list of the tasks
   1.168 +     * that were awaiting execution.
   1.169 +     *
   1.170 +     * <p>This method does not wait for actively executing tasks to
   1.171 +     * terminate.  Use {@link #awaitTermination awaitTermination} to
   1.172 +     * do that.
   1.173 +     *
   1.174 +     * <p>There are no guarantees beyond best-effort attempts to stop
   1.175 +     * processing actively executing tasks.  For example, typical
   1.176 +     * implementations will cancel via {@link Thread#interrupt}, so any
   1.177 +     * task that fails to respond to interrupts may never terminate.
   1.178 +     *
   1.179 +     * @return list of tasks that never commenced execution
   1.180 +     * @throws SecurityException if a security manager exists and
   1.181 +     *         shutting down this ExecutorService may manipulate
   1.182 +     *         threads that the caller is not permitted to modify
   1.183 +     *         because it does not hold {@link
   1.184 +     *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
   1.185 +     *         or the security manager's <tt>checkAccess</tt> method
   1.186 +     *         denies access.
   1.187 +     */
   1.188 +    List<Runnable> shutdownNow();
   1.189 +
   1.190 +    /**
   1.191 +     * Returns <tt>true</tt> if this executor has been shut down.
   1.192 +     *
   1.193 +     * @return <tt>true</tt> if this executor has been shut down
   1.194 +     */
   1.195 +    boolean isShutdown();
   1.196 +
   1.197 +    /**
   1.198 +     * Returns <tt>true</tt> if all tasks have completed following shut down.
   1.199 +     * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
   1.200 +     * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
   1.201 +     *
   1.202 +     * @return <tt>true</tt> if all tasks have completed following shut down
   1.203 +     */
   1.204 +    boolean isTerminated();
   1.205 +
   1.206 +    /**
   1.207 +     * Blocks until all tasks have completed execution after a shutdown
   1.208 +     * request, or the timeout occurs, or the current thread is
   1.209 +     * interrupted, whichever happens first.
   1.210 +     *
   1.211 +     * @param timeout the maximum time to wait
   1.212 +     * @param unit the time unit of the timeout argument
   1.213 +     * @return <tt>true</tt> if this executor terminated and
   1.214 +     *         <tt>false</tt> if the timeout elapsed before termination
   1.215 +     * @throws InterruptedException if interrupted while waiting
   1.216 +     */
   1.217 +    boolean awaitTermination(long timeout, TimeUnit unit)
   1.218 +        throws InterruptedException;
   1.219 +
   1.220 +
   1.221 +    /**
   1.222 +     * Submits a value-returning task for execution and returns a
   1.223 +     * Future representing the pending results of the task. The
   1.224 +     * Future's <tt>get</tt> method will return the task's result upon
   1.225 +     * successful completion.
   1.226 +     *
   1.227 +     * <p>
   1.228 +     * If you would like to immediately block waiting
   1.229 +     * for a task, you can use constructions of the form
   1.230 +     * <tt>result = exec.submit(aCallable).get();</tt>
   1.231 +     *
   1.232 +     * <p> Note: The {@link Executors} class includes a set of methods
   1.233 +     * that can convert some other common closure-like objects,
   1.234 +     * for example, {@link java.security.PrivilegedAction} to
   1.235 +     * {@link Callable} form so they can be submitted.
   1.236 +     *
   1.237 +     * @param task the task to submit
   1.238 +     * @return a Future representing pending completion of the task
   1.239 +     * @throws RejectedExecutionException if the task cannot be
   1.240 +     *         scheduled for execution
   1.241 +     * @throws NullPointerException if the task is null
   1.242 +     */
   1.243 +    <T> Future<T> submit(Callable<T> task);
   1.244 +
   1.245 +    /**
   1.246 +     * Submits a Runnable task for execution and returns a Future
   1.247 +     * representing that task. The Future's <tt>get</tt> method will
   1.248 +     * return the given result upon successful completion.
   1.249 +     *
   1.250 +     * @param task the task to submit
   1.251 +     * @param result the result to return
   1.252 +     * @return a Future representing pending completion of the task
   1.253 +     * @throws RejectedExecutionException if the task cannot be
   1.254 +     *         scheduled for execution
   1.255 +     * @throws NullPointerException if the task is null
   1.256 +     */
   1.257 +    <T> Future<T> submit(Runnable task, T result);
   1.258 +
   1.259 +    /**
   1.260 +     * Submits a Runnable task for execution and returns a Future
   1.261 +     * representing that task. The Future's <tt>get</tt> method will
   1.262 +     * return <tt>null</tt> upon <em>successful</em> completion.
   1.263 +     *
   1.264 +     * @param task the task to submit
   1.265 +     * @return a Future representing pending completion of the task
   1.266 +     * @throws RejectedExecutionException if the task cannot be
   1.267 +     *         scheduled for execution
   1.268 +     * @throws NullPointerException if the task is null
   1.269 +     */
   1.270 +    Future<?> submit(Runnable task);
   1.271 +
   1.272 +    /**
   1.273 +     * Executes the given tasks, returning a list of Futures holding
   1.274 +     * their status and results when all complete.
   1.275 +     * {@link Future#isDone} is <tt>true</tt> for each
   1.276 +     * element of the returned list.
   1.277 +     * Note that a <em>completed</em> task could have
   1.278 +     * terminated either normally or by throwing an exception.
   1.279 +     * The results of this method are undefined if the given
   1.280 +     * collection is modified while this operation is in progress.
   1.281 +     *
   1.282 +     * @param tasks the collection of tasks
   1.283 +     * @return A list of Futures representing the tasks, in the same
   1.284 +     *         sequential order as produced by the iterator for the
   1.285 +     *         given task list, each of which has completed.
   1.286 +     * @throws InterruptedException if interrupted while waiting, in
   1.287 +     *         which case unfinished tasks are cancelled.
   1.288 +     * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
   1.289 +     * @throws RejectedExecutionException if any task cannot be
   1.290 +     *         scheduled for execution
   1.291 +     */
   1.292 +
   1.293 +    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
   1.294 +        throws InterruptedException;
   1.295 +
   1.296 +    /**
   1.297 +     * Executes the given tasks, returning a list of Futures holding
   1.298 +     * their status and results
   1.299 +     * when all complete or the timeout expires, whichever happens first.
   1.300 +     * {@link Future#isDone} is <tt>true</tt> for each
   1.301 +     * element of the returned list.
   1.302 +     * Upon return, tasks that have not completed are cancelled.
   1.303 +     * Note that a <em>completed</em> task could have
   1.304 +     * terminated either normally or by throwing an exception.
   1.305 +     * The results of this method are undefined if the given
   1.306 +     * collection is modified while this operation is in progress.
   1.307 +     *
   1.308 +     * @param tasks the collection of tasks
   1.309 +     * @param timeout the maximum time to wait
   1.310 +     * @param unit the time unit of the timeout argument
   1.311 +     * @return a list of Futures representing the tasks, in the same
   1.312 +     *         sequential order as produced by the iterator for the
   1.313 +     *         given task list. If the operation did not time out,
   1.314 +     *         each task will have completed. If it did time out, some
   1.315 +     *         of these tasks will not have completed.
   1.316 +     * @throws InterruptedException if interrupted while waiting, in
   1.317 +     *         which case unfinished tasks are cancelled
   1.318 +     * @throws NullPointerException if tasks, any of its elements, or
   1.319 +     *         unit are <tt>null</tt>
   1.320 +     * @throws RejectedExecutionException if any task cannot be scheduled
   1.321 +     *         for execution
   1.322 +     */
   1.323 +    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
   1.324 +                                  long timeout, TimeUnit unit)
   1.325 +        throws InterruptedException;
   1.326 +
   1.327 +    /**
   1.328 +     * Executes the given tasks, returning the result
   1.329 +     * of one that has completed successfully (i.e., without throwing
   1.330 +     * an exception), if any do. Upon normal or exceptional return,
   1.331 +     * tasks that have not completed are cancelled.
   1.332 +     * The results of this method are undefined if the given
   1.333 +     * collection is modified while this operation is in progress.
   1.334 +     *
   1.335 +     * @param tasks the collection of tasks
   1.336 +     * @return the result returned by one of the tasks
   1.337 +     * @throws InterruptedException if interrupted while waiting
   1.338 +     * @throws NullPointerException if tasks or any element task
   1.339 +     *         subject to execution is <tt>null</tt>
   1.340 +     * @throws IllegalArgumentException if tasks is empty
   1.341 +     * @throws ExecutionException if no task successfully completes
   1.342 +     * @throws RejectedExecutionException if tasks cannot be scheduled
   1.343 +     *         for execution
   1.344 +     */
   1.345 +    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
   1.346 +        throws InterruptedException, ExecutionException;
   1.347 +
   1.348 +    /**
   1.349 +     * Executes the given tasks, returning the result
   1.350 +     * of one that has completed successfully (i.e., without throwing
   1.351 +     * an exception), if any do before the given timeout elapses.
   1.352 +     * Upon normal or exceptional return, tasks that have not
   1.353 +     * completed are cancelled.
   1.354 +     * The results of this method are undefined if the given
   1.355 +     * collection is modified while this operation is in progress.
   1.356 +     *
   1.357 +     * @param tasks the collection of tasks
   1.358 +     * @param timeout the maximum time to wait
   1.359 +     * @param unit the time unit of the timeout argument
   1.360 +     * @return the result returned by one of the tasks.
   1.361 +     * @throws InterruptedException if interrupted while waiting
   1.362 +     * @throws NullPointerException if tasks, or unit, or any element
   1.363 +     *         task subject to execution is <tt>null</tt>
   1.364 +     * @throws TimeoutException if the given timeout elapses before
   1.365 +     *         any task successfully completes
   1.366 +     * @throws ExecutionException if no task successfully completes
   1.367 +     * @throws RejectedExecutionException if tasks cannot be scheduled
   1.368 +     *         for execution
   1.369 +     */
   1.370 +    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
   1.371 +                    long timeout, TimeUnit unit)
   1.372 +        throws InterruptedException, ExecutionException, TimeoutException;
   1.373 +}