picture

Synchronization of Variables in Java Servlets.

One thing that one should remember about the servlets and that costs sometimes really much time to find out, why a servlet does not work properly is the synchronization of the class/servlet variables. Let us have a look at the example below:

 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.io.*;
 public class MyServlet extends HttpServlet {

   int requestCounter = 0;

   public void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {

   res.setContentType("text/plain");

   PrintWriter out = res.getWriter();

   requestCounter ++;

   out.println("MyServlet was called " + requestCounter + " times.");

   }

}

This simple servlet should show you how much times it was called by the clients since it was launched. The problem is that there is always only one instance of the servlet in the servlet container. So each time when a request is made a new Thread on the server is started. It can happen, that one request has incremented the counter, but the output is still not generated. And at this moment another request is made that changes the counter. So two clients get then the same counter value. In this simple example it's quite obvious, but think of large applications, where such inconsistences can lead to strange effects. The solution of the problem is synchronization. There are principally two ways act. You can use the key word synchronized in the method declaration. This is not so that fine, because if the method does for example some database requests, it can last very long till all the clients get the responses. Anothe possiblity is to create the synchronization section in the method like this:


synchronized(this) {

    requestCounter++;out.println( "MyServlet was called "
                                + requestCounter + " times." );
}

Although synchronization solves the discussing problem, one should always be aware of what is synchronized and that the response time can increase. The general advise is to use the local variables and to use the class variables only if there is really no other way.

Leave a Reply

For spam detection purposes, please copy the number 4398 to the field below: