Q:

What is the purpose of synchronization in session

In the below code if I don't use synchronized (this) what will happen? Is this servlet correctly cover servlet rule ?
Integer counter = new Integer(0);// instance variable

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        out.println("<html><head><title>Calculate Number of Times Visits Using Session</title></head><body>");
        HttpSession visitSession = request.getSession(true);
        if(visitSession.isNew())
            out.println("This is the first time you are visiting this page.");
        else
            out.println("Welcome back to this page");

        synchronized(this) {
            out.println("<br><br>You have visited this page " + (++Counter));
            out.println((Counter == 1) ? " time " : " times ");
        }
        out.println("</body></html>");
    } finally {
        out.close();
    }
} 

A:

It's depends on what is counter.
If counter is an instance variable of your servlet, then you must use synchronized beacause multiple threads (of the pool thread of your server) can access the same variable ("Counter") for read and write. 
In this case, if you dont's synchronized the block, could print the counter lossing some numbers( for example execute twice the "++" operation, and then twice reading, so yo lost reading un "++" operation).
If you use syncronized the output will be always
You have visited this page 1 time
You have visited this page 2 times
You have visited this page 3 times 
and so on.
If you don't use syncronized the output could be in any order for example
You have visited this page 1 time
You have visited this page 3 times
You have visited this page 3 times
You have visited this page 4 times
You have visited this page 6 times
You have visited this page 6 times 

