/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.util.Collection; import java.util.List; /** * An {@link Executor} that provides methods to manage termination and * methods that can produce a {@link Future} for tracking progress of * one or more asynchronous tasks. * *
An {@code ExecutorService} can be shut down, which will cause * it to reject new tasks. Two different methods are provided for * shutting down an {@code ExecutorService}. The {@link #shutdown} * method will allow previously submitted tasks to execute before * terminating, while the {@link #shutdownNow} method prevents waiting * tasks from starting and attempts to stop currently executing tasks. * Upon termination, an executor has no tasks actively executing, no * tasks awaiting execution, and no new tasks can be submitted. An * unused {@code ExecutorService} should be shut down to allow * reclamation of its resources. * *
Method {@code submit} extends base method {@link * Executor#execute(Runnable)} by creating and returning a {@link Future} * that can be used to cancel execution and/or wait for completion. * Methods {@code invokeAny} and {@code invokeAll} perform the most * commonly useful forms of bulk execution, executing a collection of * tasks and then waiting for at least one, or all, to * complete. (Class {@link ExecutorCompletionService} can be used to * write customized variants of these methods.) * *
The {@link Executors} class provides factory methods for the * executor services provided in this package. * *
{@code * class NetworkService implements Runnable { * private final ServerSocket serverSocket; * private final ExecutorService pool; * * public NetworkService(int port, int poolSize) * throws IOException { * serverSocket = new ServerSocket(port); * pool = Executors.newFixedThreadPool(poolSize); * } * * public void run() { // run the service * try { * for (;;) { * pool.execute(new Handler(serverSocket.accept())); * } * } catch (IOException ex) { * pool.shutdown(); * } * } * } * * class Handler implements Runnable { * private final Socket socket; * Handler(Socket socket) { this.socket = socket; } * public void run() { * // read and service request on socket * } * }}* * An {@code ExecutorService} may also be established and closed * (shutdown, blocking until terminated) as follows; illustrating with * a different {@code Executors} factory method: * *
{@code * try (ExecutorService e = Executors.newWorkStealingPool()) { * // submit or execute many tasks with e ... * }}* * Further customization is also possible. For example, the following * method shuts down an {@code ExecutorService} in two phases, first * by calling {@code shutdown} to reject incoming tasks, and then * calling {@code shutdownNow}, if necessary, to cancel any lingering * tasks: * *
{@code * void shutdownAndAwaitTermination(ExecutorService pool) { * pool.shutdown(); // Disable new tasks from being submitted * try { * // Wait a while for existing tasks to terminate * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { * pool.shutdownNow(); // Cancel currently executing tasks * // Wait a while for tasks to respond to being cancelled * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) * System.err.println("Pool did not terminate"); * } * } catch (InterruptedException ex) { * // (Re-)Cancel if current thread also interrupted * pool.shutdownNow(); * // Preserve interrupt status * Thread.currentThread().interrupt(); * } * }}* *
Memory consistency effects: Actions in a thread prior to the * submission of a {@code Runnable} or {@code Callable} task to an * {@code ExecutorService} * happen-before * any actions taken by that task, which in turn happen-before the * result is retrieved via {@code Future.get()}. * * @since 1.5 * @author Doug Lea */ public interface ExecutorService extends Executor, AutoCloseable { /** * Initiates an orderly shutdown in which previously submitted * tasks are executed, but no new tasks will be accepted. * Invocation has no additional effect if already shut down. * *
This method does not wait for previously submitted tasks to * complete execution. Use {@link #awaitTermination awaitTermination} * to do that. * * @throws SecurityException if a security manager exists and * shutting down this ExecutorService may manipulate * threads that the caller is not permitted to modify * because it does not hold {@link * java.lang.RuntimePermission}{@code ("modifyThread")}, * or the security manager's {@code checkAccess} method * denies access. */ void shutdown(); /** * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a list of the tasks * that were awaiting execution. * *
This method does not wait for actively executing tasks to * terminate. Use {@link #awaitTermination awaitTermination} to * do that. * *
There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks. For example, typical
* implementations will cancel via {@link Thread#interrupt}, so any
* task that fails to respond to interrupts may never terminate.
*
* @return list of tasks that never commenced execution
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
*/
List
* If you would like to immediately block waiting
* for a task, you can use constructions of the form
* {@code result = exec.submit(aCallable).get();}
*
* Note: The {@link Executors} class includes a set of methods
* that can convert some other common closure-like objects,
* for example, {@link java.security.PrivilegedAction} to
* {@link Callable} form so they can be submitted.
*
* @param task the task to submit
* @param If interrupted while waiting, this method stops all executing tasks as
* if by invoking {@link #shutdownNow()}. It then continues to wait until all
* actively executing tasks have completed. Tasks that were awaiting
* execution are not executed. The interrupt status will be re-asserted
* before this method returns.
*
* If already terminated, invoking this method has no effect.
*
* @implSpec
* The default implementation invokes {@code shutdown()} and waits for tasks
* to complete execution with {@code awaitTermination}.
*
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
* @since 19
*/
@Override
default void close() {
boolean terminated = isTerminated();
if (!terminated) {
shutdown();
boolean interrupted = false;
while (!terminated) {
try {
terminated = awaitTermination(1L, TimeUnit.DAYS);
} catch (InterruptedException e) {
if (!interrupted) {
shutdownNow();
interrupted = true;
}
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}