Java Reference
In-Depth Information
10.8 Concurrency utilities in J2SE 5.0
As mentioned in Chapter 8 on threads in Java, release 5.0 adds numerous enhance-
ments to the threading control and concurrency features of Java. Some of the
enhancements are advanced features beyond the scope of this topic, but we explain
some of the simpler new features here.
10.8.1 The Executor class
The most important new feature for the casual developer of multithreaded
applications is the new Executor framework. A java.util.concurrent.
Executor is an object that executes submitted Runnable tasks. In that regard,
it is similar to calling
new Thread (aRunnable).start ();
Forasingle new thread, there is perhaps not much reason to use an Executor .
However, most multithreaded applications involve several threads. Threads need
stack and heap space, and, depending on the platform, thread creation can be
expensive. In addition, cancellation and shutdown of threads can be difficult, as
seen in Chapter 8, and a well-designed and implemented thread pooling scheme
is not simple. The new Executor framework solves all those problems in a way
that decouples task submission from the mechanics of how each task will be run,
including details of thread use, scheduling, etc.
An Executor can and should be used instead of explicitly creating threads.
Forexample, rather than creating a new thread and starting it as above, you can
use:
Executor executor = some Executor factory method ;
exector.execute (aRunnable);
Notice that our Executor object was returned by an Executor factory. (As
we discuss in Chapter 16, a “factory” is a standard name for a method that is
used to obtain an instance of a class or subclass rather than making it with a
constructor.) There are several static Executor factory methods available in the
java.util.concurrent.Executors class. If you have several Runnable
tasks to carry out, but do not have specific requirements about the order in which
they occur, as is commonly the case, then a simple thread pool arrangement is
needed:
Executor executor = Executors.newFixedThreadPool (5);
executor.execute (new RunnableTask1 ());
executor.execute (new RunnableTask2 ());
executor.execute (new RunnableTask3 ());
...
Search WWH ::




Custom Search