I am trying to make a servlet thread-safe by synchronizing a block of code.The counter needs to count how many times a page has been visited.But it starts at 2 and when i refresh the page, it increments by 2(so it goes 2,4,6).I tried to remove the object variable while preserving the functionality but to no avail.what is missing in my code?
here is my servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count extends HttpServlet
{
private int visitCount = 0;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
synchronized(this){
visitCount++;
request.setAttribute("counter", visitCount);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
public String getServletInfo()
{
return "Short description";
}// </editor-fold>
}