[英]What is the purpose of synchronization in session
在下面的代码中,如果我不使用同步(此),将会发生什么? 这个servlet是否正确覆盖了servlet规则?
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();
}
}
这取决于什么是计数器。
如果counter是Servlet的实例变量,则必须使用同步,因为(服务器池线程的)多个线程可以访问同一变量(“ Counter”)进行读写。
在这种情况下,如果您不同步该块,则可以打印丢失一些数字的计数器(例如,执行两次“ ++”操作,然后两次读取,因此您无法读取“ ++”操作)。
如果使用同步化,输出将始终为
You have visited this page 1 time You have visited this page 2 times You have visited this page 3 times
等等。
如果您不使用同步化,则输出可以是任何顺序,例如
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()中声明为线程安全,在这种情况下,不需要同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.