Wednesday, 12 November 2014

Thread Safe JSP Page

I was looking for whether there is any way to make our jsp thread safe.
I came across something like You just need to set an attribute to tell the container whether your jsp is thread safe or not.

<%@ page isThreadSafe="false" %>

By Default this attribute is true.

If we use this page attribute in jsp,only one thing changes in the generated servlet code.
Now servlet class implements SingleThreadModel Interface.




As of Java Servlet API 2.4
interface SingleThreadModel
Ensures that servlets handle only one request at a time. This interface has no methods.
If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.





Syntax of isThreadSafe attribute is: <%@ page isThreadSafe="true|false" %>

If this attribute is true which is default value,then container may send multiple concurrent requests simultaneously by starting a thread each time and if it false,Container will only send one request at a time and in the order they were received.

Whether your jsp is thread safe or not,depends totally on the way it was implemented.
Normally jsps are thread safe because your run of the JSP does not hold any member variables.

But if you use <%! %>,this will place the code at the class level not in the service method.
Now this introduction makes jsp unsafe.