Executor vs ExecutorService in Java

1. Introduction

In Java concurrency, Executor and ExecutorService are part of the Java Executor Framework, which simplifies task execution in asynchronous mode. Executor is an interface that provides a way of decoupling task submission from the mechanics of how each task will be run. ExecutorService is a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.

2. Key Points

1. Executor is a simple interface that supports launching new tasks.

2. ExecutorService extends Executor, providing methods to manage termination and methods that can produce a Future for tracking the progress of one or more asynchronous tasks.

3. An Executor does not provide any control over the execution policies or the tasks after they are submitted.

4. ExecutorService can be shut down, which allows previously submitted tasks to execute before terminating.

3. Differences

Executor ExecutorService
Provides a way to submit tasks. Adds lifecycle management of both tasks and the executor itself.
Does not provide any mechanism to control or track tasks after submission. Provides methods to track and control tasks' progress via Future objects.
It cannot be managed once initiated; it lacks shutdown capabilities. It can be shut down; we are awaiting the completion of the submitted tasks.

4. Example

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class ExecutorVsExecutorService {
    public static void main(String[] args) {
        Executor executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> System.out.println("Task executed with Executor"));

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> System.out.println("Task executed with ExecutorService"));
        executorService.shutdown(); // Initiates an orderly shutdown
    }
}

Output:

Task executed with Executor
Task executed with ExecutorService

Explanation:

1. Executor example simply executes a task to print a statement.

2. ExecutorService does the same but demonstrates the ability to shut down the executor, which Executor does not have.

5. When to use?

- Use Executor when you want a simple mechanism to execute asynchronous tasks.

- Use ExecutorService when you need a more complete asynchronous task execution framework, including the ability to manage and track the progress of tasks and to shut down the executor gracefully.

Comments