Java Reference
In-Depth Information
The concurrency utilities provide executors as a high-level alternative to low-level
ThreadingAPIexpressionsforexecutingrunnabletasks.An executor isanobjectwhose
class directly or indirectly implements the java.util.concurrent.Executor
interface, which decouples task submission from task-execution mechanics.
Note Theexecutorframework'suseofinterfacestodecoupletasksubmissionfrom
task-executionmechanicsisanalogoustotheCollectionsFramework'suseofcorein-
terfaces todecouplelists,sets,queues,deques,andmapsfromtheirimplementations.
Decoupling results in flexible code that is easier to maintain.
Executor declaresasolitary void execute(Runnable runnable) method
that executes the runnable task named runnable at some point in the future. ex-
ecute() throws java.lang.NullPointerException when runnable is
null , and java.util.concurrent.RejectedExecutionException
when it cannot execute runnable .
Note RejectedExecutionException can be thrown when an executor is
shutting down and does not want to accept new tasks. Also, this exception can be
thrown when the executor does not have enough room to store the task (perhaps the
executorusesaboundedblockingqueuetostoretasksandthequeueisfull—Idiscuss
blocking queues later in this chapter).
The following example presents the Executor equivalent of the aforementioned
new Thread(new RunnableTask()).start(); expression:
Executor executor = ...; // ... represents some executor
creation
executor.execute(new RunnableTask());
Although Executor is easy to use, this interface is limited in various ways:
Executor focusesexclusivelyon Runnable .Because Runnable 's run()
methoddoesnotreturnavalue,thereisnoconvenientwayforarunnabletask
to return a value to its caller.
Executor doesnotprovideawaytotracktheprogressofexecutingrunnable
tasks, cancel an executing runnable task, or determine when the runnable task
finishes execution.
Executor cannot execute a collection of runnable tasks.
Executor doesnotprovideawayforanapplicationtoshutdownanexecutor
(much less to properly shut down an executor).
Search WWH ::




Custom Search