15

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?

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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!
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.
Servlets also have to be thread safe because they share state information with other servlets (objects such as those stored in ServletContext and HttpSession)
So, do you mean one thread for your request to get access only one servlet instance?
1

Historically you had 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.

Comments

1

yes,there is a interface single thread model .it is a marker interface. it makes this object of servlet synchronized i.e at a time only one thread serve the object.but it create the problems like response delay.for solution they create pool of objects but again pool also has limited size.so it is better to use synchronized block

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.