Thejava.util.concurrent
package defines three executor interfaces:Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type.
Executor
, a simple interface that supports launching new tasks.ExecutorService
, a subinterface ofExecutor
, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.ScheduledExecutorService
, a subinterface ofExecutorService
, supports future and/or periodic execution of tasks.The
TheExecutor
InterfaceExecutor
interface provides a single method,execute
, designed to be a drop-in replacement for a common thread-creation idiom. Ifr
is aRunnable
object, ande
is anExecutor
object you can replacewith(new Thread(r)).start();However, the definition ofe.execute(r);execute
is less specific. The low-level idiom creates a new thread and launches it immediately. Depending on theExecutor
implementation,execute
may do the same thing, but is more likely to use an existing worker thread to runr
, or to placer
in 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.concurrent
are designed to make full use of the more advancedExecutorService
andScheduledExecutorService
interfaces, although they also work with the baseExecutor
interface.The
TheExecutorService
InterfaceExecutorService
interface supplementsexecute
with a similar, but more versatilesubmit
method. Likeexecute
,submit
acceptsRunnable
objects, but also acceptsCallable
objects, which allow the task to return a value. Thesubmit
method returns aFuture
object, which is used to retrieve theCallable
return value and to manage the status of bothCallable
andRunnable
tasks.
ExecutorService
also provides methods for submitting large collections ofCallable
objects. Finally,ExecutorService
provides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts correctly.The
TheScheduledExecutorService
InterfaceScheduledExecutorService
interface supplements the methods of its parentExecutorService
withschedule
, which executes aRunnable
orCallable
task after a specified delay. In addition, the interface definesscheduleAtFixedRate
andscheduleWithFixedDelay
, which executes specified tasks repeatedly, at defined intervals.