Java Reference
In-Depth Information
Figure 11-2.
New Managed Executor Service Panel
This panel offers quite a few options for creation of the service. However, the only option that is required is the
JNDI Name, as all others are populated with default values. The JNDI name that is specified should follow the format
of
concurrent/YourExecutorServiceName
, where
YourExecutorServiceName
is a custom name of your choice.
Running the Reporter Task
After the
ManagedExecutorService
has been created, it can be utilized by one or more applications to
perform concurrent operations. An application must be either configured via XML to allow access to the
ManagedExecutorService
resource in the application server container, or the resource can be injected via the use of
the
@Resource
annotation. In the example, each of these options is demonstrated. For the purposes of the example, it
is assumed that the
@Resource
annotation is utilized to inject the service into the servlet.
To run a task concurrently using the service, you must create the task in a separate class that implements
java.util.Runnable
, so that it can be invoked as a separate process, much like a standard Java
Thread
. In the
example, a class named
ReporterTask
implements
Runnable
, and within the run method the reporter task performs
the tasks that we wish to run in an asynchronous manner. In the case of this example, a couple of methods are
invoked from within the run method. The
Runnable
class that has been generated can then be passed to the
ManagedExecutorService
to be executed concurrently while other tasks are being performed by the application.