[英]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.