Link to home
Start Free TrialLog in
Avatar of GAUTAM
GAUTAMFlag for United States of America

asked on

Doubt in Servlet

Hello Guys,

I have a servlet code which maintains the number of times its is accessed.

At a certain point on the doGet method the point where the incrementation is done for number of times accessed that part is synchronized.

Can anyone elaborate why that is done and what are the effects if the synchronization is not done in the doGet method.

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

public class FirstAccessed extends HttpServlet{

    private Date first;
    private int count;

    public void init() throws ServletException {

        // Enter the time/date when the server calls this servlet and
        // initialize counter
    first = new Date();
        count = 0;
        return;

    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
        res.setContentType("text/plain");
        PrintWriter out = res.getWriter();
    int local_count;
    synchronized(this) {
        local_count = ++count;
    }
        out.println("<HTML>");
        out.println("<HEAD><TITLE>First Accessed Servlet</TITLE></HEAD>");
        out.println("<BODY>");
    out.println("This servlet was first loaded by the server at " + first);
    out.println("<br>The current time is " + new Date());
    out.println("<br>");
    out.println("This servlet has been accessed " + local_count + " times.");
        out.println("</BODY></HTML>");
    }



}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:)