Servlet Seems to Handle Multiple Concurrent Browser Requests Synchronously

Servlet seems to handle multiple concurrent browser requests synchronously

Your browser is apparently using the same HTTP connection in different windows. The servlet container uses a single thread per HTTP connection, not per HTTP request. You should run two physically different webbrowsers to test this properly. E.g. one Firefox and one Chrome.

How does a single servlet handle multiple requests from client side

Struts/Spring frameworks are actually written on top of Servlet specification so doesn't matter what you use underneath it use Servlets.

You are right, Only single instance of Servlet is created, but that instance is shared across multiple threads. For this reason you should never have shared mutable states in your Servlets.

For example you have following servlet mapped to http://localhost/myservlet

class MySerlvet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) {
// Get Logic
}
}

The Web Server will have something similar (Not necessarily same) in its code.

MyServlet m = new MyServlet(); // This will be created once

// for each request for http://localhost/myservlet
executorService.submit(new RequestProcessingThread(m));

Preventing concurrent access to a method in servlet

One way you could solve the problem is by using a synchronized block. There are many things you could choose as your locking object - for the moment this should be fine:

class BookingService {
public void insert(Booking t) {
synchronized(this) {
if(available(t.getTutor(), t.getDate(), t.getTime())) {
bookingDao.insert(t);
} else {
// reject
}
}
}
}

If you have more than one instance of the servlet, then you should use a static object as a lock.



Related Topics



Leave a reply



Submit