简体   繁体   English

会话中同步的目的是什么

[英]What is the purpose of synchronization in session

In the below code if I don't use synchronized (this) what will happen? 在下面的代码中,如果我不使用同步(此),将会发生什么? Is this servlet correctly cover servlet rule ? 这个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();
    }
} 

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. 如果counter是Servlet的实例变量,则必须使用同步,因为(服务器池线程的)多个线程可以访问同一变量(“ Counter”)进行读写。

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()中声明为线程安全,在这种情况下,不需要同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM