Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet: Singleton, Singlethread or Multi Instance Multithread

Tags:

java

jsp

servlets

This question has been asked previously and discussed before but i want to ask it further.

  1. Are Servlets Singleton or not ? According to me they are initialized only by the container but they are still not singleton ?? why ??

  2. Are Servlets Single Thread or multi Threaded (Forget about javax.servlet.SingleThreadModel class) i.e. What happens when there are multiple requests for a single servlet ?? If they are executed conncurrently, that means it is multi threaded ?? and if its multi threaded then each thread will have an instance of the servlet, which contradicts with the 1st point !!

What i think is, Whenever theres a new request, The container creates a new Thread for the incoming Request say Req1, in that it calls or dispatches the control to the service method of servlet. Now this execution happens concurrenlty.. i guess so...

Does my working stands the same in a MVC envirionment ?? (say Struts 1/2, Springs)

like image 701
vipul12389 Avatar asked Jun 06 '13 12:06

vipul12389


3 Answers

The fact that exists just one instance doesn't means it isn't multithread. More thread can concurrently call tha same method of the same instance. Servlets are absolutly multithread.

like image 111
mauretto Avatar answered Oct 02 '22 15:10

mauretto


Servlets are multithreaded - this is the base for their efficiency. One can use "implements SingleThreadModel" to make a servlet single-threaded, so for every request a new object will be created.

Recently this interface SingleThreadModel was deprecated

like image 31
Alex Avatar answered Oct 02 '22 17:10

Alex


It depends on the implementation. The servlet interface doesn't specify. http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html

However, if you see the HttpServlet then you can see it specifies that it should be synchronized. http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServlet.html

like image 30
Funkytown Avatar answered Oct 02 '22 16:10

Funkytown