Java Reference
In-Depth Information
In this example, a ManagedThreadFactory will be injected into an EJB, so that a logging task can be used to print
output to the server log when the EJB is created or destroyed. The following code demonstrates how to create a task
that can be utilized by the ManagedThreadFactory :
public class MessagePrinter implements Runnable {
public void run() {
public void printMessage(){
System.out.println("Here we are performing some work...");
To initiate the threading, call the ManagedThreadFactory , which can be injected into a using class via the
@Resource annotation. The ManageThreadFactory newThread method can then be invoked to spawn a new thread,
passing the Runnable class instance for which the thread should process. In the servlet context listener example
below, when a thread context is initialized, then a Runnable class that was listed in the previous code listing,
MessagePrinter , is instantiated and passed to the ManagedThreadFactory to spawn a new thread.
package org.javaee7.chapter11;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedThreadFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
* Servlet Context Listener: Prints message when context is initialized
* @author Juneau
public class ServletCtxListener implements ServletContextListener {
Thread printerThread = null;
@Resource(name ="concurrent/AcmeThreadFactory")
ManagedThreadFactory threadFactory;
public void contextInitialized(ServletContextEvent scEvent) {
MessagePrinter printer = new MessagePrinter();
Thread loggerThread = threadFactory.newThread(printer);
Search WWH ::

Custom Search