Table of Contents

Java Concurrency - Executor (Thread manager)

About

An executor is a thread management module (thread creation and management).

Java.util.concurrent

java.util.concurrent provides two executor interfaces:

Executor

Executor is a simple standardized interface for defining custom thread-like subsystems, including:

Depending on which concrete Executor class is being used, tasks may:

An object that executes submitted Runnable tasks.

An Executor is normally used instead of explicitly creating threads.

Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());

ExecutorService

ExecutorService is more extensive interface Executor by providing a more complete asynchronous task execution framework.

An ExecutorService manages:

ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable.

The ScheduledExecutorService subinterface and associated interfaces add support for:

task execution.

Example

In a producer-consumer context:

// Start the threads
ExecutorService targetWorkExecutor = Executors.newFixedThreadPool(targetWorkerCount);
targetWorkExecutor.execute(resultSetLoaderConsumer);

// Wait the producer
producer.join();
producerWorkIsDone.set(true);

// Shut down the targetWorkExecutor
targetWorkExecutor.shutdown();
// And wait the termination of the threads
targetWorkExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MICROSECONDS);