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>
}

It looks like it is calling processRequest twice. Could you try and change your doPost() to...

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
}

and you may need to declare visitCount as static?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.