background image

Creating Polite Long-Running Methods

<< Tracking Service Requests | More about Java Servlet Technology >>
<< Tracking Service Requests | More about Java Servlet Technology >>

Creating Polite Long-Running Methods

...
//Access methods for shuttingDown
protected synchronized void setShuttingDown(boolean flag) {
shuttingDown = flag;
}
protected synchronized boolean isShuttingDown() {
return shuttingDown;
}
}
Here is an example of the destroy method using these fields to provide a clean shutdown:
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 Methods
The 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 shutdowns and should interrupt their work, if necessary.
public void doPost(...) {
...
for(i = 0; ((i < lotsOfStuffToDo) &&
!isShuttingDown()); i++) {
try {
partOfLongRunningOperation(i);
} catch (InterruptedException e) {
...
}
}
}
Finalizing a Servlet
The Java EE 5 Tutorial · September 2007
130