Thejava.util.concurrentpackage 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
TheExecutorInterfaceExecutorinterface provides a single method,execute, designed to be a drop-in replacement for a common thread-creation idiom. Ifris aRunnableobject, andeis anExecutorobject you can replacewith(new Thread(r)).start();However, the definition ofe.execute(r);executeis less specific. The low-level idiom creates a new thread and launches it immediately. Depending on theExecutorimplementation,executemay do the same thing, but is more likely to use an existing worker thread to runr, or to placerin 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 advancedExecutorServiceandScheduledExecutorServiceinterfaces, although they also work with the baseExecutorinterface.The
TheExecutorServiceInterfaceExecutorServiceinterface supplementsexecutewith a similar, but more versatilesubmitmethod. Likeexecute,submitacceptsRunnableobjects, but also acceptsCallableobjects, which allow the task to return a value. Thesubmitmethod returns aFutureobject, which is used to retrieve theCallablereturn value and to manage the status of bothCallableandRunnabletasks.
ExecutorServicealso provides methods for submitting large collections ofCallableobjects. Finally,ExecutorServiceprovides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts correctly.The
TheScheduledExecutorServiceInterfaceScheduledExecutorServiceinterface supplements the methods of its parentExecutorServicewithschedule, which executes aRunnableorCallabletask after a specified delay. In addition, the interface definesscheduleAtFixedRateandscheduleWithFixedDelay, which executes specified tasks repeatedly, at defined intervals.