Like it or not, a servlet must be capable of serving more than one client at a time. Built-in threading capability is one of the key reasons why Java is so well-suited to server applications, particularly when compared to a traditional CGI model. As usual, however, tradeoffs are involved. In particular, writing code that can handle many concurrent tasks without corrupting data can be quite challenging at times. Ideally, this material can alert you to the most common causes of threading problems found in a servlet environment.
In the standard servlet model, a client makes a request via the
service( ) method. In the
HttpServlet class, the
service( ) method determines the type of HTTP request and delegates
to methods such as
doGet( ) or
doPost( ). If several clients issue requests at the same time,
these methods will serve each client in a different thread. Since
most servlets are subclasses of
main concern is insuring that
doGet( ), and
doPost( ) can
handle many concurrent clients.
Before handling any requests, a servlet’s
init( ) method is invoked. According to the servlet API
specification, this method must be invoked by only a single thread
and must complete successfully before subsequent threads are allowed
to enter the
service( ) method. For this reason,
you do not have to worry about threading problems inside of the
init( ) method. From there, however, all bets are
One simplistic approach ...