Java Reference
In-Depth Information
Figure 11-6.
New Managed Thread Factory panel
As mentioned in the example, an application can make use of a
ManagedThreadFactory
resource by configuring
XML within the
web.xml
deployment descriptor, or by injecting via the
@Resource
annotation within the classes that
need to make use of the resource. Once that resource has been injected, calls can be made against it to spawn new
threads using the
newThread
method. The
newThread
method returns a Thread instance, which can then be utilized
by calling the
Thread
instance methods, as needed. In the example, the thread is started by calling the thread's
start
method, and when the context is destroyed, the thread's
interrupt
method is invoked.
To utilize a
ManagedThreadFactory
, the environment must be configured via XML or annotation. To utilize XML
configuration, add a
<resource-env-ref>
element to the
web.xml
deployment descriptor. In this case, you need to
configure a resource of type
javax.enterprise.concurrent.ManagedThreadFactory
, as shown in the excerpt from
the
web.xml
below:
<resource-env-ref>
<description>
</description>
<resource-env-ref-name>
concurrent/AcmeThreadFactory
</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.concurrent.ManagedThreadFactory
</resource-env-ref-type>
</resource-env-ref>
To utilize annotations rather than XML configuration, the
ManagedThreadFactory
can be injected using an
annotation such as the following:
@Resource(name="concurrent/AcmeThreadFactory");
ManagedThreadFactory threadFactory;