We know that either by extending Thread or by implementing Runnable, we can create a thread. But in Servlet API, we do not have any such class which extends Thread or implementing Runnable, atleast the classes HttpServlet is extending. I assume that , container would create a new thread for every request and that thread would use a single instance of Servlet. But does this mean that Servlet is designed using Singleton pattern?
Please let me know, how multithreading is implemented in Servlets.
Thanks Ravi C.Kota
Thanks & Regards, SK
SCJP 5.0, DB2 - 800, DB2 - 803, SCDJWS (On the way)
I assume that , container would create a new thread for every request
That is correct.
... and that thread would use a single instance of Servlet.
No. Servlets are multi-threaded, so all threads use the same servlet instance. That's why it is important to write servlets in a thread-safe manner (e.g., by not using instance variables that can change over time).
But does this mean that Servlet is designed using Singleton pattern?
That pattern is overused, IMO, and doesn't really help understanding what's going on here. (For completeness' sake it should be noted that servlet containers may instantiate more than one instance under certain circumstances, so it isn't strictly true anyway.)
I have an extension of my query. We know that while creating a thread, we either pass a thread or runnable object as a parameter or a zero arguement constructor. But my question is how does container link a newly created thread with the one time created Servlet object. I have this question, because I'm thinking how could thread access the servlet object, as servlet neither extends thread nor implements runnable. I know that my question is a bit vague,but could not express it more than this.
Thanks Ravi C.Kota
Joined: Mar 22, 2005
A class that implements Runnable can have references to any objects you pass into it, either via the constructor or via setter method. The run method then uses those instance variables as it sees fit. No problem at all :-)