ExecutorService

About

The ExecutorService in Java is part of the java.util.concurrent package and provides a higher-level replacement for working with threads directly. It simplifies the management and control of thread execution and task scheduling. It abstracts away the complexities of thread management, allowing developers to focus on the core logic of their tasks.

Core Concepts

1. Executor Interface

  • The Executor interface provides a single method, execute(Runnable command), to submit a task for execution. It is a interface designed to decouple task submission from the mechanics of how each task will be run.

public interface Executor {

    /**
     * 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.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

Example

2. ExecutorService Interface

  • The ExecutorService interface extends the Executor interface, adding lifecycle management methods and more flexible task submission methods. It provides a higher-level abstraction for managing and controlling the execution of asynchronous tasks.

ExecutorService Interface

Key Methods:

  1. Task Submission:

    • Future<?> submit(Runnable task): Submits a Runnable task for execution and returns a Futurerepresenting that task.

    • <T> Future<T> submit(Callable<T> task): Submits a Callable task for execution and returns a Futurerepresenting the task's result.

  2. Task Management:

    • <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks): Executes the given tasks, returning a list of Future objects representing the tasks.

    • <T> T invokeAny(Collection<? extends Callable<T>> tasks): Executes the given tasks, returning the result of one that has completed successfully.

  3. Lifecycle Management:

    • void shutdown(): Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

    • List<Runnable> shutdownNow(): Attempts to stop all actively executing tasks and returns a list of the tasks that were awaiting execution.

    • boolean isShutdown(): Returns true if this executor has been shut down.

    • boolean isTerminated(): Returns true if all tasks have completed following a shutdown.

    • boolean awaitTermination(long timeout, TimeUnit unit): Blocks until all tasks have completed after a shutdown request, or the timeout occurs, or the current thread is interrupted.

3. Thread Pool

  • A thread pool is a pool of worker threads that can be reused to execute multiple tasks. The thread pool reduces the overhead of thread creation and destruction by reusing existing threads. It is a collection of pre-instantiated reusable threads that can be used to execute tasks. It helps to manage and limit the number of active threads, improving performance and resource management.

Key Concepts:

  • Core Pool Size: The number of threads to keep in the pool, even if they are idle.

  • Maximum Pool Size: The maximum number of threads allowed in the pool.

  • Keep Alive Time: The maximum time that excess idle threads will wait for new tasks before terminating.

  • Work Queue: A queue used to hold tasks before they are executed.

Common Implementations:

  • Fixed Thread Pool: A pool with a fixed number of threads.

  • Cached Thread Pool: A pool that creates new threads as needed but will reuse previously constructed threads when they are available.

  • Scheduled Thread Pool: A pool that can schedule commands to run after a given delay or to execute periodically.

  • Single Thread Executor: A pool with a single thread to execute tasks sequentially.

4. ExecutorService Implementations

  • Fixed Thread Pool (Executors.newFixedThreadPool(int nThreads)): A pool with a fixed number of threads.

  • Cached Thread Pool (Executors.newCachedThreadPool()): A pool that creates new threads as needed but will reuse previously constructed threads when they are available.

  • Scheduled Thread Pool (Executors.newScheduledThreadPool(int corePoolSize)): A pool that can schedule commands to run after a given delay or to execute periodically.

  • Single Thread Executor (Executors.newSingleThreadExecutor()): A pool with a single thread to execute tasks sequentially

Last updated