In all of the previous examples, there’s a close connection between the task being done by a new thread, as defined by its
Runnable object, and the thread itself, as defined by a
Thread object. This works well for small applications, but in large-scale applications, it makes sense to separate thread management and creation from the rest of the application. Objects that encapsulate these functions are known as executors. The following subsections describe executors in detail.
- Executor Interfaces define the three executor object types.
- Thread Pools are the most common kind of executor implementation.
- Fork/Join is a framework (new in JDK 7) for taking advantage of multiple processors.
java.util.concurrentpackage defines three executor interfaces:
Executor, a simple interface that supports launching new tasks.
ExecutorService, a subinterface of
Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
ScheduledExecutorService, a subinterface of
ExecutorService, supports future and/or periodic execution of tasks.
Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type.
Executorinterface provides a single method,
execute, designed to be a drop-in replacement for a common thread-creation idiom. If
Executorobject you can replace
However, the definition of
executeis less specific. The low-level idiom creates a new thread and launches it immediately. Depending on the
executemay do the same thing, but is more likely to use an existing worker thread to run
r, or to place
rin a queue to wait for a worker thread to become available. (We’ll describe worker threads in the section on Thread Pools.)
The executor implementations in
java.util.concurrentare designed to make full use of the more advanced
ScheduledExecutorServiceinterfaces, although they also work with the base
executewith a similar, but more versatile
Runnableobjects, but also accepts
Callableobjects, which allow the task to return a value. The
submitmethod returns a
Futureobject, which is used to retrieve the
Callablereturn value and to manage the status of both
ExecutorServicealso provides methods for submitting large collections of
ExecutorServiceprovides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts correctly.
ScheduledExecutorServiceinterface supplements the methods of its parent
schedule, which executes a
Callabletask after a specified delay. In addition, the interface defines
scheduleWithFixedDelay, which executes specified tasks repeatedly, at defined intervals.