troubleshooting Question

Doubt in Servlet

Avatar of gaugeta
gaugeta asked on
JavaJSPJava EE
2 Comments1 Solution417 ViewsLast Modified:
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>");
    }



}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros