ExecutorService

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.

<p>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.

<p>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.)

<p>The {@link Executors} class provides factory methods for the executor services provided in this package.

<h3>Usage Examples</h3>

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured {@link Executors#newFixedThreadPool} factory method:

<pre> {@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 } }}</pre>

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:

<pre> {@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 ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }}</pre>

<p>Memory consistency effects: Actions in a thread prior to the submission of a {@code Runnable} or {@code Callable} task to an {@code ExecutorService} <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> any actions taken by that task, which in turn <i>happen-before</i> the result is retrieved via {@code Future.get()}.

@author Doug Lea

Members

Functions

awaitTermination
bool awaitTermination(Duration timeout)

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

isShutdown
bool isShutdown()

Returns {@code true} if this executor has been shut down.

isTerminated
bool isTerminated()

Returns {@code true} if all tasks have completed following shut down. Note that {@code isTerminated} is never {@code true} unless either {@code shutdown} or {@code shutdownNow} was called first.

shutdown
void shutdown()

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.

shutdownNow
List!(Runnable) shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

Inherited Members

From Executor

execute
void execute(Runnable command)

Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the {@code Executor} implementation.

Meta