Servlet Threads

In the AuditFilter example, several lines of code were encased in a synchronize block. This was done to ensure that the counter would be correctly incremented if more than one access is made to the page at the same time. Without the synchronize block, it is possible for two (or possibly more) servlet threads to obtain the counter value before it has been incremented, thereby losing one of the increments. In this case, failing to count one page hit is not a significant problem. There are other situations where it might be.

Shared resources, such as files and databases, can also present concurrency issues when accessed by more than one servlet at a time. To avoid concurrency issues, a servlet can implement the single-thread model.

Note

The servlet init() method is only called once, so concurrency is not a problem here.


The servlet API specifies that a servlet container must guarantee that no two threads of a servlet that implements the javax.servlet.SingleThreadModel interface are run concurrently. This means the container must maintain a pool of servlet instances and dispatch each new request to a free servlet; otherwise, only one request at a time can be handled.

If you want to make your servlet single threaded to prevent concurrency problems, simply add the SingleThreadModel interface to the class signature.

public class HTMLPage extends HttpServlet implements SingleThreadModel {

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.79.65