jdk/src/share/classes/java/util/concurrent/ExecutorService.java
changeset 2 90ce3da70b43
child 61 5691b03db1ea
equal deleted inserted replaced
0:fd16c54261b3 2:90ce3da70b43
       
     1 /*
       
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     3  *
       
     4  * This code is free software; you can redistribute it and/or modify it
       
     5  * under the terms of the GNU General Public License version 2 only, as
       
     6  * published by the Free Software Foundation.  Sun designates this
       
     7  * particular file as subject to the "Classpath" exception as provided
       
     8  * by Sun in the LICENSE file that accompanied this code.
       
     9  *
       
    10  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    13  * version 2 for more details (a copy is included in the LICENSE file that
       
    14  * accompanied this code).
       
    15  *
       
    16  * You should have received a copy of the GNU General Public License version
       
    17  * 2 along with this work; if not, write to the Free Software Foundation,
       
    18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    19  *
       
    20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
       
    21  * CA 95054 USA or visit www.sun.com if you need additional information or
       
    22  * have any questions.
       
    23  */
       
    24 
       
    25 /*
       
    26  * This file is available under and governed by the GNU General Public
       
    27  * License version 2 only, as published by the Free Software Foundation.
       
    28  * However, the following notice accompanied the original version of this
       
    29  * file:
       
    30  *
       
    31  * Written by Doug Lea with assistance from members of JCP JSR-166
       
    32  * Expert Group and released to the public domain, as explained at
       
    33  * http://creativecommons.org/licenses/publicdomain
       
    34  */
       
    35 
       
    36 package java.util.concurrent;
       
    37 import java.util.List;
       
    38 import java.util.Collection;
       
    39 import java.security.PrivilegedAction;
       
    40 import java.security.PrivilegedExceptionAction;
       
    41 
       
    42 /**
       
    43  * An {@link Executor} that provides methods to manage termination and
       
    44  * methods that can produce a {@link Future} for tracking progress of
       
    45  * one or more asynchronous tasks.
       
    46  *
       
    47  * <p> An <tt>ExecutorService</tt> can be shut down, which will cause
       
    48  * it to reject new tasks.  Two different methods are provided for
       
    49  * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown}
       
    50  * method will allow previously submitted tasks to execute before
       
    51  * terminating, while the {@link #shutdownNow} method prevents waiting
       
    52  * tasks from starting and attempts to stop currently executing tasks.
       
    53  * Upon termination, an executor has no tasks actively executing, no
       
    54  * tasks awaiting execution, and no new tasks can be submitted.  An
       
    55  * unused <tt>ExecutorService</tt> should be shut down to allow
       
    56  * reclamation of its resources.
       
    57  *
       
    58  * <p> Method <tt>submit</tt> extends base method {@link
       
    59  * Executor#execute} by creating and returning a {@link Future} that
       
    60  * can be used to cancel execution and/or wait for completion.
       
    61  * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
       
    62  * commonly useful forms of bulk execution, executing a collection of
       
    63  * tasks and then waiting for at least one, or all, to
       
    64  * complete. (Class {@link ExecutorCompletionService} can be used to
       
    65  * write customized variants of these methods.)
       
    66  *
       
    67  * <p>The {@link Executors} class provides factory methods for the
       
    68  * executor services provided in this package.
       
    69  *
       
    70  * <h3>Usage Examples</h3>
       
    71  *
       
    72  * Here is a sketch of a network service in which threads in a thread
       
    73  * pool service incoming requests. It uses the preconfigured {@link
       
    74  * Executors#newFixedThreadPool} factory method:
       
    75  *
       
    76  * <pre>
       
    77  * class NetworkService implements Runnable {
       
    78  *   private final ServerSocket serverSocket;
       
    79  *   private final ExecutorService pool;
       
    80  *
       
    81  *   public NetworkService(int port, int poolSize)
       
    82  *       throws IOException {
       
    83  *     serverSocket = new ServerSocket(port);
       
    84  *     pool = Executors.newFixedThreadPool(poolSize);
       
    85  *   }
       
    86  *
       
    87  *   public void run() { // run the service
       
    88  *     try {
       
    89  *       for (;;) {
       
    90  *         pool.execute(new Handler(serverSocket.accept()));
       
    91  *       }
       
    92  *     } catch (IOException ex) {
       
    93  *       pool.shutdown();
       
    94  *     }
       
    95  *   }
       
    96  * }
       
    97  *
       
    98  * class Handler implements Runnable {
       
    99  *   private final Socket socket;
       
   100  *   Handler(Socket socket) { this.socket = socket; }
       
   101  *   public void run() {
       
   102  *     // read and service request on socket
       
   103  *   }
       
   104  * }
       
   105  * </pre>
       
   106  *
       
   107  * The following method shuts down an <tt>ExecutorService</tt> in two phases,
       
   108  * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
       
   109  * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
       
   110  *
       
   111  * <pre>
       
   112  * void shutdownAndAwaitTermination(ExecutorService pool) {
       
   113  *   pool.shutdown(); // Disable new tasks from being submitted
       
   114  *   try {
       
   115  *     // Wait a while for existing tasks to terminate
       
   116  *     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       
   117  *       pool.shutdownNow(); // Cancel currently executing tasks
       
   118  *       // Wait a while for tasks to respond to being cancelled
       
   119  *       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
       
   120  *           System.err.println("Pool did not terminate");
       
   121  *     }
       
   122  *   } catch (InterruptedException ie) {
       
   123  *     // (Re-)Cancel if current thread also interrupted
       
   124  *     pool.shutdownNow();
       
   125  *     // Preserve interrupt status
       
   126  *     Thread.currentThread().interrupt();
       
   127  *   }
       
   128  * }
       
   129  * </pre>
       
   130  *
       
   131  * <p>Memory consistency effects: Actions in a thread prior to the
       
   132  * submission of a {@code Runnable} or {@code Callable} task to an
       
   133  * {@code ExecutorService}
       
   134  * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
       
   135  * any actions taken by that task, which in turn <i>happen-before</i> the
       
   136  * result is retrieved via {@code Future.get()}.
       
   137  *
       
   138  * @since 1.5
       
   139  * @author Doug Lea
       
   140  */
       
   141 public interface ExecutorService extends Executor {
       
   142 
       
   143     /**
       
   144      * Initiates an orderly shutdown in which previously submitted
       
   145      * tasks are executed, but no new tasks will be accepted.
       
   146      * Invocation has no additional effect if already shut down.
       
   147      *
       
   148      * @throws SecurityException if a security manager exists and
       
   149      *         shutting down this ExecutorService may manipulate
       
   150      *         threads that the caller is not permitted to modify
       
   151      *         because it does not hold {@link
       
   152      *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
       
   153      *         or the security manager's <tt>checkAccess</tt> method
       
   154      *         denies access.
       
   155      */
       
   156     void shutdown();
       
   157 
       
   158     /**
       
   159      * Attempts to stop all actively executing tasks, halts the
       
   160      * processing of waiting tasks, and returns a list of the tasks that were
       
   161      * awaiting execution.
       
   162      *
       
   163      * <p>There are no guarantees beyond best-effort attempts to stop
       
   164      * processing actively executing tasks.  For example, typical
       
   165      * implementations will cancel via {@link Thread#interrupt}, so any
       
   166      * task that fails to respond to interrupts may never terminate.
       
   167      *
       
   168      * @return list of tasks that never commenced execution
       
   169      * @throws SecurityException if a security manager exists and
       
   170      *         shutting down this ExecutorService may manipulate
       
   171      *         threads that the caller is not permitted to modify
       
   172      *         because it does not hold {@link
       
   173      *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
       
   174      *         or the security manager's <tt>checkAccess</tt> method
       
   175      *         denies access.
       
   176      */
       
   177     List<Runnable> shutdownNow();
       
   178 
       
   179     /**
       
   180      * Returns <tt>true</tt> if this executor has been shut down.
       
   181      *
       
   182      * @return <tt>true</tt> if this executor has been shut down
       
   183      */
       
   184     boolean isShutdown();
       
   185 
       
   186     /**
       
   187      * Returns <tt>true</tt> if all tasks have completed following shut down.
       
   188      * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
       
   189      * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
       
   190      *
       
   191      * @return <tt>true</tt> if all tasks have completed following shut down
       
   192      */
       
   193     boolean isTerminated();
       
   194 
       
   195     /**
       
   196      * Blocks until all tasks have completed execution after a shutdown
       
   197      * request, or the timeout occurs, or the current thread is
       
   198      * interrupted, whichever happens first.
       
   199      *
       
   200      * @param timeout the maximum time to wait
       
   201      * @param unit the time unit of the timeout argument
       
   202      * @return <tt>true</tt> if this executor terminated and
       
   203      *         <tt>false</tt> if the timeout elapsed before termination
       
   204      * @throws InterruptedException if interrupted while waiting
       
   205      */
       
   206     boolean awaitTermination(long timeout, TimeUnit unit)
       
   207         throws InterruptedException;
       
   208 
       
   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(Collection<? extends Callable<T>> tasks)
       
   283         throws InterruptedException;
       
   284 
       
   285     /**
       
   286      * Executes the given tasks, returning a list of Futures holding
       
   287      * their status and results
       
   288      * when all complete or the timeout expires, whichever happens first.
       
   289      * {@link Future#isDone} is <tt>true</tt> for each
       
   290      * element of the returned list.
       
   291      * Upon return, tasks that have not completed are cancelled.
       
   292      * Note that a <em>completed</em> task could have
       
   293      * terminated either normally or by throwing an exception.
       
   294      * The results of this method are undefined if the given
       
   295      * collection is modified while this operation is in progress.
       
   296      *
       
   297      * @param tasks the collection of tasks
       
   298      * @param timeout the maximum time to wait
       
   299      * @param unit the time unit of the timeout argument
       
   300      * @return a list of Futures representing the tasks, in the same
       
   301      *         sequential order as produced by the iterator for the
       
   302      *         given task list. If the operation did not time out,
       
   303      *         each task will have completed. If it did time out, some
       
   304      *         of these tasks will not have completed.
       
   305      * @throws InterruptedException if interrupted while waiting, in
       
   306      *         which case unfinished tasks are cancelled
       
   307      * @throws NullPointerException if tasks, any of its elements, or
       
   308      *         unit are <tt>null</tt>
       
   309      * @throws RejectedExecutionException if any task cannot be scheduled
       
   310      *         for execution
       
   311      */
       
   312     <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
       
   313                                   long timeout, TimeUnit unit)
       
   314         throws InterruptedException;
       
   315 
       
   316     /**
       
   317      * Executes the given tasks, returning the result
       
   318      * of one that has completed successfully (i.e., without throwing
       
   319      * an exception), if any do. Upon normal or exceptional return,
       
   320      * tasks that have not completed are cancelled.
       
   321      * The results of this method are undefined if the given
       
   322      * collection is modified while this operation is in progress.
       
   323      *
       
   324      * @param tasks the collection of tasks
       
   325      * @return the result returned by one of the tasks
       
   326      * @throws InterruptedException if interrupted while waiting
       
   327      * @throws NullPointerException if tasks or any of its elements
       
   328      *         are <tt>null</tt>
       
   329      * @throws IllegalArgumentException if tasks is empty
       
   330      * @throws ExecutionException if no task successfully completes
       
   331      * @throws RejectedExecutionException if tasks cannot be scheduled
       
   332      *         for execution
       
   333      */
       
   334     <T> T invokeAny(Collection<? extends Callable<T>> tasks)
       
   335         throws InterruptedException, ExecutionException;
       
   336 
       
   337     /**
       
   338      * Executes the given tasks, returning the result
       
   339      * of one that has completed successfully (i.e., without throwing
       
   340      * an exception), if any do before the given timeout elapses.
       
   341      * Upon normal or exceptional return, tasks that have not
       
   342      * completed are cancelled.
       
   343      * The results of this method are undefined if the given
       
   344      * collection is modified while this operation is in progress.
       
   345      *
       
   346      * @param tasks the collection of tasks
       
   347      * @param timeout the maximum time to wait
       
   348      * @param unit the time unit of the timeout argument
       
   349      * @return the result returned by one of the tasks.
       
   350      * @throws InterruptedException if interrupted while waiting
       
   351      * @throws NullPointerException if tasks, any of its elements, or
       
   352      *         unit are <tt>null</tt>
       
   353      * @throws TimeoutException if the given timeout elapses before
       
   354      *         any task successfully completes
       
   355      * @throws ExecutionException if no task successfully completes
       
   356      * @throws RejectedExecutionException if tasks cannot be scheduled
       
   357      *         for execution
       
   358      */
       
   359     <T> T invokeAny(Collection<? extends Callable<T>> tasks,
       
   360                     long timeout, TimeUnit unit)
       
   361         throws InterruptedException, ExecutionException, TimeoutException;
       
   362 }