troubleshooting Question

Doubt in Servlet

Avatar of gaugeta
gaugeta asked on
Java EEJSPJava
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 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;


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


Open in new window

Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
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