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
Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
new Thread(command).start();
}
};
executor.execute(() -> System.out.println("Task executed"));
// Anonymous new Executor() can be replaced with lambda
Executor executor = command -> new Thread(command).start();
executor.execute(() -> System.out.println("Task executed"));
2. ExecutorService Interface
The
ExecutorService
interface extends theExecutor
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.
Key Methods:
Task Submission:
Future<?> submit(Runnable task)
: Submits aRunnable
task for execution and returns aFuture
representing that task.<T> Future<T> submit(Callable<T> task)
: Submits aCallable
task for execution and returns aFuture
representing the task's result.
Task Management:
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
: Executes the given tasks, returning a list ofFuture
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.
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()
: Returnstrue
if this executor has been shut down.boolean isTerminated()
: Returnstrue
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
Was this helpful?