A Runnable class can be created to house the procedure for polling the database and creating the alerts. The following PGM1 shows that Runnable that will be used to create the managed thread. In this example, a class named ReservationAlerter. That class can then be made into a thread by calling a ManagedThreadFactory’s newThread() method, as shown in PGM2.
PGM1:
public
class ReservationAlerter implements Runnable {
@Override
public void run() {
while (!Thread.interrupted()) {
reviewReservations();
try {
Thread.sleep(100000);
} catch (InterruptedException ex) {
// Log error
}
}
}
public Collection reviewReservations() {
Connection conn = null;
Properties connectionProps = new
Properties();
connectionProps.put("user",
"user");
connectionProps.put("password",
"password");
Collection reservations = null;
try {
// Obtain connection and retrieve
reservations
conn = DriverManager.getConnection(
"jdbc:derby:acme;create=false",
connectionProps);
// Use the connection to query the
database for reservations
} catch (SQLException ex){
System.out.println("Exception:
" + ex);
} finally {
if (conn != null){
try {
conn.close();
} catch (SQLException ex) {
// Log error
}
}
}
return reservations;
}
}
PGM2:
ReservationAlerter alerter = new
ReservationAlerter();
alerterThread =
threadFactory.newThread(alerter);
alerterThread.start();
PGM3 shows the complete code for obtaining a reference to the ManagedThreadFactory via @Resource injection, creating the new Thread instance, and then starting it.
PGM3:
public class AcmeAlerterContextListener
implements ServletContextListener {
Thread alerterThread = null;
@Resource(name="concurrent/__defaultManagedThreadFactory")
ManagedThreadFactory threadFactory;
@Override
public void contextInitialized(ServletContextEvent sce) {
ReservationAlerter alerter = new ReservationAlerter();
alerterThread = threadFactory.newThread(alerter);
alerterThread.start();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
if(alerterThread!=null){
alerterThread.interrupt();
}
}
}
l y a g �� д 0pt;margin-right:.5in;margin-bottom:
6.0pt;margin-left:0in;line-height:normal;mso-pagination:none;mso-layout-grid-align:
none;text-autospace:none'> Properties connectionProps = new
Properties();
connectionProps.put("user",
"user");
connectionProps.put("password",
"password");
Collection reservations = null;
try {
// Obtain connection and retrieve
reservations
conn = DriverManager.getConnection(
"jdbc:derby:acme;create=false",
connectionProps);
// Use the connection to query the
database for reservations
} catch (SQLException ex){
System.out.println("Exception:
" + ex);
} finally {
if (conn != null){
try {
conn.close();
} catch (SQLException ex) {
// Log error
}
}
}
return reservations;
}
}
No comments:
Post a Comment