background image

Finalizing a Servlet

<< Session Tracking | Tracking Service Requests >>
<< Session Tracking | Tracking Service Requests >>

Finalizing a Servlet

"</a> &nbsp; &nbsp; &nbsp;" +
"<a href=\"" +
response.encodeURL(request.getContextPath() +
"/bookcashier") +
"\">" + messages.getString("Checkout") +
"</a> &nbsp; &nbsp; &nbsp;" +
"<a href=\"" +
response.encodeURL(request.getContextPath() +
"/bookshowcart?Clear=clear") +
"\">" + messages.getString("ClearCart") +
"</a></strong>");
If cookies are turned off, the session is encoded in the Check Out URL as follows:
http://localhost:8080/bookstore1/cashier;jsessionid=c0o7fszeb1
If cookies are turned on, the URL is simply
http://localhost:8080/bookstore1/cashier
Finalizing a Servlet
When a servlet container determines that a servlet should be removed from service (for
example, when a container wants to reclaim memory resources or when it is being shut down),
the container calls the destroy method of the Servlet interface. In this method, you release
any resources the servlet is using and save any persistent state. The following destroy method
releases the database object created in the init method described in
"Initializing a Servlet" on
page 109
:
public void destroy() {
bookDB = null;
}
All of a servlet's service methods should be complete when a servlet is removed. The server tries
to ensure this by calling the destroy method only after all service requests have returned or
after a server-specific grace period, whichever comes first. If your servlet has operations that
take a long time to run (that is, operations that may run longer than the server's grace period),
the operations could still be running when destroy is called. You must make sure that any
threads still handling client requests complete; the remainder of this section describes how to
do the following:
Keep track of how many threads are currently running the service method.
Provide a clean shutdown by having the destroy method notify long-running threads of the
shutdown and wait for them to complete.
Have the long-running methods poll periodically to check for shutdown and, if necessary,
stop working, clean up, and return.
Finalizing a Servlet
The Java EE 5 Tutorial · September 2007
128