Java.util.concurrent Executors

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

An executor is a mechanism that allows executing tasks on a thread different than the one that submits the task for execution. Executors are preferred to explicitly creating Thread instances. The executor decouples the task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.

The essential interface is java.util.concurrent.Executor, which defines an object that executes submitted Runnable or Callable tasks. Note that the Executor interface does not strictly require that execution be asynchronous - in the simplest case the executor can run the submitted Runnable immediately, in the caller's thread - though asynchronous execution in some other thread than the caller's is generally the case.

Once it submitted a task for execution, the caller can be notified of task execution, asynchronously, via a Future.

java.util.concurrent.ExecutorService extends java.util.concurrent.Executor and allows the instance implementing it to be shut down, which will cause it to reject new tasks. Upon termination, an executor service instance has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. Upon creation, an ExecutorService is started and ready to accept tasks by default.

The package offers an executor instance factory class java.util.concurrent.Executors, which is in general recommended to be used when a new executor is needed.

Typical Usage

int threadCount = 10;
ExecutorService executor = Executors.newFixedThreadPool(threadCount);

...

executor.execute(() -> { ... });

The ExecutorService so created has a fixed number of threads operating off a shared unbounded queue. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.