0

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();
    }
} 
mohsen.nour
  • 1,089
  • 3
  • 20
  • 27
  • What is `Counter`? A class? A class member? –  Nov 17 '14 at 11:03
  • I think `Counter` is an integer value, indicating visit count. Is ur servlet used in Multithreaded environment ? – OO7 Nov 17 '14 at 11:08
  • 1
    @OO7 that's obvious. But if it were a `Integer` it would be immutable ... – Fildor Nov 17 '14 at 11:10
  • Integer counter = new Integer(0); – mohsen.nour Nov 17 '14 at 11:17
  • @mohsen.noor - obviously Counter is an Integer, but its not clear from your code where it comes from - is it a static member of your servlet, an instance member, a static import from a separate class etc.. it could be any of these as the declaration is not shown in the sample and its scope has a big impact on how it should be handled correctly in a multi-threaded environment. – Tom Bunting Nov 17 '14 at 11:20
  • As told by @Fildor Integer would be immutable. Have a look at [Is Integer Immutable](http://stackoverflow.com/questions/5560176/is-integer-immutable) & for use of `synchronized` it is already answered here [What does 'synchronized' mean ?](http://stackoverflow.com/questions/1085709/what-does-synchronized-mean) – OO7 Nov 17 '14 at 11:21
  • @tombola82 sorry. It is an instance member – mohsen.nour Nov 17 '14 at 11:25

2 Answers2

1

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

  • Just to add, remember that the pre/post increment/decrement operators (++/--) are NOT atomic and actually represent 3 distinct operations - read-modify-write, making it even more important to synchronize access in multi-threaded environments. – Tom Bunting Nov 17 '14 at 11:44
0

since the counter (variable) is globally declared it will not be a thread safe one, in order to make it thread safe declare it inside the goGet() in which case the synchronized is unnecessary.

srinigowda
  • 80
  • 9