Executors in Action – Part 1 – The Life cycle

From the Javadoc

… interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads.

Indeed, Executors provide a more robust and easy mechanism for decoupling of submitting a task, from its execution.

In this series, we shall explore this concurrency construct in detail.

NOTE: Have tried to avoid explaining what is already available in javadoc.

Let’s first see the lifecycle of an Executor

ExecutorService extends the Executor interface, adding a bunch of life cycle methods.

Executor Life Cycle

Executor Life Cycle


Let’s create a simple program to demonstrate the same

public static void main(String[] args) {
// Executor doesn't exist before this step
// Executor created and moved to running state
ExecutorService executor = Executors.newSingleThreadExecutor();

// Executor into running state
executor.execute(new Runnable() {
public void run() {
System.out.println("Running...");
}
});

// Lets shutdown
executor.shutdown();

System.out.println(" isShutdown = "+executor.isShutdown());
System.out.println(" isTermianted = "+executor.isTerminated());
}

The program depicts the complete lifecycle. Please see the comments inline in the code

Initially the Executor doesn’t exist. When we create an Executor, using Executor’s we have it in Ready state (ready to accept tasks for execution).
Once we submit a task for execution, the Executor moves to running state. Once it completes the task, it moves back to ready state.

Once we call shutdown() on Executor, it begins its shutdown cycle. Once it is completed it moves to Terminated state.

There are couple of things that need to be noted after shutdown is initiated. An Executor can be executing or may have couple of tasks pending to be executed.

Calling shutdown() initiates an orderly shutdown, means all the pending tasks shall be completed, but new tasks won’t be accepted

Calling shutdownNow() initiates a shutdown, by trying to halt the processing the tasks by interrupting the threads. The method returns a list of Runnable’s which were not executed. Programs can use them to reschedule them later or discard them.

What will happen, if we submit a task once shutdown has been initiated?
This situation can be handled by using RejectExecutionHandler. The default implementation simply discards the tasks. We can have the custom logic to handle the tasks that couldn’t be executed.

Upcoming topic – Exploring a little on ScheduledExecutorService

One thought on “Executors in Action – Part 1 – The Life cycle

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.