|
|
|
|||
|
Handling Service Threads at Servlet TerminationAll of a servlet's service methods should be complete when a servlet is
removed. The server tries to ensure this by calling the
If your servlet has potentially long-running service requests, use the
techniques in this lesson to:
Tracking Service RequestsTo track service requests, include a field in your servlet class that counts the number of service methods that are running. The field should have access methods to increment, decrement, and return its value. For example:
The
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
enteringServiceMethod();
try {
super.service(req, resp);
} finally {
leavingServiceMethod();
}
}
Providing a Clean ShutdownTo provide a clean shutdown, your destroy method should not destroy any shared resources until all the service requests have completed. One part of doing this is to check the service counter. Another part is to notify the long-running methods that it is time to shut down. For this, another field is required along with the usual access methods. For example:
An example of the
public void destroy() {
/* Check to see whether there are still service methods running,
* and if there are, tell them to stop. */
if (numServices() > 0) {
setShuttingDown(true);
}
/* Wait for the service methods to stop. */
while(numServices() > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
}
Creating Polite Long-running MethodsThe final step in providing a clean shutdown is to make any long-running methods behave politely. Methods that might run for a long time should check the value of the field that notifies them of shut downs, and interrupt their work if neceesary. For example:
public void doPost(...) {
...
for(i = 0; ((i < lotsOfStuffToDo) && !isShuttingDown()); i++) {
try {
partOfLongRunningOperation(i);
} catch (InterruptedException e) {
}
}
}
| |||
|