Java Concurrency - Executor (Thread manager)
> Procedural Languages > Java > Java - Concurrency (Parallel Work)
Table of Contents
1 - About
An executor is a thread management module (thread creation and management).
2 - Articles Related
3 - Java.util.concurrent
java.util.concurrent provides two executor interfaces:
3.1 - Executor
Executor is a simple standardized interface for defining custom thread-like subsystems, including:
- thread pools,
- asynchronous I/O,
- and lightweight task frameworks.
Depending on which concrete Executor class is being used, tasks may:
- execute in:
- a newly created thread,
- an existing task-execution thread,
- or the thread calling execute,
- and may execute
- sequentially
- or concurrently.
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());
3.2 - ExecutorService
ExecutorService is more extensive interface Executor by providing a more complete asynchronous task execution framework.
An ExecutorService manages:
- queuing
- scheduling of tasks,
- and controlled shutdown.
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:
- delayed
- and periodic
task execution.
4 - 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);