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();
}
}
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
由于计数器(变量)是全局声明的,因此它不是线程安全的,为了使其在goGet()中声明为线程安全,在这种情况下,不需要同步。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.