Monday, September 29, 2008

Thread Safety in JSP & Servlet

You can thread safe your jsp (java server pages) pages in two ways

1. By implementing the SingleThreadModel interface.

This is done by adding the directive to your jsp page

<%@ page isThreadSafe=”false” %>

Within your jsp page.

When you implement SingleThreadModel interface instead of a single instance of the servlet generated for your jsp page loaded in memory, jsp engine creates new instance of that jsp page for each client request.
but avoid this method because, this methods has some performance issue and there are many pitfalls.

2. By using synchronized block or synchronized method

(a) synchronized block
when you expect that more than 2 threads may operate on your code (means om jsp page) and they may inconsistent your data then used synchronized block on particular object
e.g.

import javax.servlet.*;
import javax.servlet.http.*;
import java.math.*;
import java.io.*;

public class testServlet extends HttpServlet
{
//A variable that is NOT thread-safe!
private int cnt = 0;
private String str = “”;

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.getWriter().println(”");
resp.getWriter().println(this + “:
“);
synchronized (str)
{
for (int c = 0; c < counter =" ”">

This string is called a str and is shared among all threads, thus ensure that at time one thread can access code block, if another thread want to enter code block then 1st thread must leave that block.

(b) Synchronized method
A whole method can be synchronized, just you need to add synchronized keyword in method signature.

e.g.
public synchronized void show()
{
// your code
}

Other precautions

To be thread safe in your JSP, do not declared variables in <%! %> tags. variables that declared in declaration tag are not thread safe.

Attributes.
Page level attributes are threadsafe.
Request level attributes are threadsafe, as long as you forward in a linear fashion. i.e. forward from servlet to JSP, and ensure that no more code runs in the servlet after forwarding.
Session level attributes: potentially not thread safe if one user makes multiple requests (eg clicks twice on a link/button)
application level attributes: not thread safe at all.

Also consider any resources that you pick up from session attributes/singletons etc as potentially not threadsafe.

No comments: