1

I defined a servlet(map it to /index) and rewrite the doPost method like this :

private Object lock = new Object();
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("start");
        synchronized(lock) {
            try {
                lock.wait(15000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.notifyAll();
        }
    }

when the first request comes in, it prints 'start' then waits at lock.wait(15000); then the second request comes, and it should be blocked at synchronized(lock); as i thought. But the fact is the second request is blocked out of the doPost method. After the first request goes lock.notifyAll(); then the second request comes into doPost method and prints 'start'.

I found this only happens when two requests query the exactly same url. Is this the way that Tomcat handles for multi-thread ?? I am so confused..

Michael
  • 402
  • 1
  • 3
  • 16
  • Please refer to [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/q/3106452/1065197) to have a better understanding on how the Java Web Application Servers (not Tomcat only) works with `Servlet`s and `Thread`s. By the way, you **must never** use this kind of code in a Web Application (at least that you want to get fired). – Luiggi Mendoza Feb 25 '13 at 08:54
  • `fired` ? I think they will look for who hired ? – Apurv Feb 25 '13 at 09:03

1 Answers1

0

Only the doPost and doGet method of the servlet are thread safe, means for each thread they are invoked independently. The class itself is instantiated only once.
In the code above you are acquiring lock on class variable which will be shared across all request, hence you are getting that locked per request.

To get your expected behaviour move your 'Objectinstantiation insidedoPost` method.

  • The questions says `Request blocking in doPost()` so I believe this is what is the required/expected behavior – Apurv Feb 25 '13 at 09:02