简体   繁体   中英

Servlet GLOBAL Variable concurrent access

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?

Servlet instance variables are not thread safe. Since there is only one copy of the servlet created and different threads, created for each incoming request, share the instance variables. Hence concurrent access for servlet class instance variables should be well guarded. Use of AtomicInteger for your counters should help!

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

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.

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