Results 1 to 2 of 2
  1. #1
    mohsen.noor is offline Member
    Join Date
    Dec 2012
    Rep Power

    Default What is the purpose of synchronization in this code

    Hi everyone in the below code if I don't use synchronized (this) what will happen?

    Java Code:
    package servlet;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    @WebServlet(name="CalculationVisitServlet", urlPatterns={"/CalculationVisitServlet"})
    public class CalculationVisitServlet extends HttpServlet {
        private int Counter;
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            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);
                    out.println("This is the first time you are visiting this page.");
                    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 ");
            } finally {
    Last edited by mohsen.noor; 11-17-2014 at 06:44 AM.

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Rep Power

    Default Re: What is the purpose of synchronization in this code

    A Servlet class has only one instance, so synchronizing on this in a servlet will make it so all HTTP requests to that servlet will update that counter variable one at a time.

    Basically this code breaks all the rules - a servlet should never have properties, it must be "stateless".
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. interface purpose?
    By frejon26 in forum New To Java
    Replies: 5
    Last Post: 06-27-2014, 10:41 AM
  2. What is the purpose of Java?
    By ShadowWalker in forum New To Java
    Replies: 7
    Last Post: 06-24-2014, 10:08 AM
  3. Constructors. What is their purpose?
    By BenH in forum New To Java
    Replies: 2
    Last Post: 05-22-2012, 09:44 AM
  4. What is the purpose of a HashMap?
    By Tombomb in forum New To Java
    Replies: 4
    Last Post: 01-17-2012, 12:04 PM
  5. Purpose of close() ?
    By fatabass in forum New To Java
    Replies: 4
    Last Post: 01-13-2012, 10:57 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts