Executors

Executor provides an abstraction layer over all the internal thread management tasks and manages the entire concurrent execution flow of the threads. An Executor is an object that executes tasks provided.

The Java concurrency API provides the following three basic interfaces for executors:

  • Executor: This is a simple interface that is used to launch a new task. It does not strictly require the execution to be asynchronous.
  • ExecutorService: This is a subinterface of the Executor interface. It allows us to pass a task to be executed by a thread asynchronously. It provides methods to manage the termination of previously sublimed tasks through shutdown(), shutdownNow(), and awaitTermination(long timeout, TimeUnit unit). It also provides methods that return the Future object for tracking the progress of one or more asynchronous tasks.
  • ScheduledExecutorService: This is a subinterface of ExecutorService. It provides various key methods, such as schedule(), scheduleAtFixedRate() and scheduleWithFixedDelay(). All schedule methods can accept relative delays and periods as arguments, and this helps us to schedule tasks to execute after a given delay or period.

The following is a simple example showing how to create Executor in order to execute a Runnable task:

public class ExecutorExample {
private static final Logger LOGGER =
Logger.getLogger(ExecutorExample.class);

public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();

Runnable task = new Runnable() {
public void run() {
LOGGER.info(Thread.currentThread().getName());
}
};

pool.execute(task);
pool.shutdown();
}
}

In the previous example, a Runnable object is created by an anonymous class and executes a task by means of a single-threaded Executor interface. When we compile and run the preceding class, we will get the following output:

pool-1-thread-1
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset