How to implement a thread-safe JSP page?

A thread-safe JSP/servlet is one that works correctly when more than one thread is running at the same time. To make your JSPs thread-safe, you can implement the SingleThreadModel interface that prevents two threads from accessing the service method at the same time.

The JSP page by default is not thread safe, if you want to make it thread safe then you have add the following directive in your JSP page declaration:

<%@ page isThreadSafe="false" %>

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine

Whether your JSP is thread-safe or not is a consequence of the way you implemented your JSP. Strictly speaking you cannot change that simply by modifying an attribute. JSPs are normally perfectly thread-safe, since your run of the JSP does not hold any state (member variables).

For example, if you happen to use <%! %>, this will place the code in class level and not in the _jspService method. You introduce class member into the JSP object that makes JSP becomes thread-unsafe.

If your JSP is not thread-safe you will have to add the isThreadSafe=false in order for things to work correctly. Such way, it does not make your JSP thread-safe but it does make your web application thread-safe by instructing the servlet container to cater for the thread-unsafety of your JSP:

  • If isThreadSafe=true then the JSP container may choose to dispatch multiple outstanding client requests to the page simultaneously. Page authors using true must ensure that they properly synchronize access to the shared state of the page.
  • If isThreadSafe=false then the JSP container shall dispatch multiple outstanding client requests, one at a time, in the order they were received, to the page implementation for processing.

Note that even if the isThreadSafe attribute is false the JSP page author must ensure that accesses to any shared objects are properly synchronized., The objects may be shared in either the ServletContext or the HttpSession.

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |