0

I have servlet printingServlet and have two Global variables linesPrinted and pages

    public class printingServlet extends HttpServlet {
       int linesPrinted = -3;
       int pages = 0;

       ----
       ----
      protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

             //print some lines
             //increment linesPrinted  and pages

             //call function2,function3,function4,Checkfunction
       }
      public void function1(){

          //print some lines
          // increment linesPrinted and pages
          //call Checkfunction
      }
      public void function2(){

          //print some lines
          // increment linesPrinted and pages
          //call Checkfunction
      }
      public void function3(){

          //print some lines
          // increment linesPrinted and pages
          //call Checkfunction
      }
      public void Checkfunction(){

          // check linesPrinted and pages
          // Do some stuff if specific values are reached else continue
      } 



all @override methods   
    }

This works fine when only one user calls this servlet, but lately it shows some problems in page and lines calculation when requests are concurrently sent to the servlet.

When the request that created error is requested without any concurrent requests then it works fine.

What should be done to avoid such a problem?

4

1 回答 1

1

Servlet 实例变量不是线程安全的。由于只创建了一个 servlet 副本,并且为每个传入请求创建的不同线程共享实例变量。因此,应该很好地保护对 servlet 类实例变量的并发访问。将 AtomicInteger 用于您的计数器应该会有所帮助!

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html

于 2013-07-06T06:37:48.713 回答