views:

56

answers:

2

I was wondering if anybody could explains me the threading model of Java Servlets? As I understood about that, there is only one instance of a servlet can be existed in the servlet container and if muliple threads happens to be waiting for that servlet, there requests are serialized in some manner. I don't know how that serialization process happens...

Can anybody explain it?

+4  A: 

If requests were handled serially by servlets, then web applications would be very slow. It's actually the case that servlets need to be thread-safe, because a single instance of a servlet can be responsible for handling multiple requests simultaneously.

Usually a web application container will maintain a thread pool for handling requests, with incoming requests being assigned to threads on an on-demand basis.

danben
Thanks in advance for the reply danben!But I have one more thing to clarify.Being thread-safe means there is no internal state maintained in a servlet.So any servlet instance resides in the pool has the same state as they were created.Am I correct?Thanks!
Dunith Dhanushka
A class with no internal state is thread-safe, but it is not the only way to be thread-safe. Thread-safety itself is a long discussion, but for example, a class with internal state can be thread-safe if it serializes access to its internal state.
danben
Servlets also have to be thread safe because they share state information with other servlets (objects such as those stored in ServletContext and HttpSession)
Paul Rayner
A: 

Historically you add two models, depending on your Servlet. If the Servlet implemented SingleThreadModel, then the requests where queued. Otherwise, and this is the only model now, a Servlet must be able to serve multiple requests at the same time. So there is no queueing in that model, unless the container has some rate-limiting functionnality.

Damien B