Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
38
Chapter 2 First Servlets
automatically uses the status line and header settings of
doGet
to answer
HEAD
requests.
The SingleThreadModel Interface
Normally, the system makes a single instance of your servlet and then creates
a new thread for each user request, with multiple simultaneous threads run
ning if a new request comes in while a previous request is still executing. This
means that your
doGet
and
doPost
methods must be careful to synchronize
access to fields and other shared data, since multiple threads may be trying to
access the data simultaneously. See Section 7.3 (Persistent Servlet State and
Auto Reloading Pages) for more discussion of this. If you want to prevent this
multithreaded access, you can have your servlet implement the
SingleTh
readModel
interface, as below.
public class YourServlet extends HttpServlet
implements SingleThreadModel {
...
}
If you implement this interface, the system guarantees that there is never
more than one request thread accessing a single instance of your servlet. It
does so either by queuing up all the requests and passing them one at a time
to a single servlet instance, or by creating a pool of multiple instances, each of
which handles one request at a time. This means that you don't have to worry
about simultaneous access to regular fields (instance variables) of the servlet.
You do, however, still have to synchronize access to class variables (
static
fields) or shared data stored outside the servlet.
Synchronous access to your servlets can significantly hurt performance
(latency) if your servlet is accessed extremely frequently. So think twice
before using the
SingleThreadModel
approach.
The destroy Method
The server may decide to remove a previously loaded servlet instance, per
haps because it is explicitly asked to do so by the server administrator, or per
haps because the servlet is idle for a long time. Before it does, however, it
calls the servlet's
destroy
method. This method gives your servlet a chance
to close database connections, halt background threads, write cookie lists or
hit counts to disk, and perform other such cleanup activities. Be aware, how
ever, that it is possible for the Web server to crash. After all, not all Web serv
ers are written in reliable programming languages like Java; some are written
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved