I have read that code in servlets can be synchronized with synchronized blocks. However, I have also read that whilst there is often only one instance of a servlet the servlet container may keep a pool of instances. Surely this means that a synchronized block is therefore not guaranteed to work as you don't know which instance the request thread will choose?
-
2I think you should read these 2 answers from BalusC: [How do servlets work?](http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909) and [Servlet's instances](http://stackoverflow.com/questions/2183974/difference-each-instance-of-servlet-and-each-thread-of-servlet-in-servlets/2184147#2184147) – Mr.J4mes Dec 31 '11 at 11:20
-
2Thanks, the consensus from those 2 answers is that 1 instance per servlet is used so synchronization will work – Jon Dec 31 '11 at 11:59
3 Answers
Section 2.2 of the specification (3.0) says:
For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration
So, if a container uses a pool of instances, it's in violation of the spec. I don't see why a container would do that, since every servlet developers know that multiple threads may access the servlet concurrently, and the servlet must thus be thread-safe.

- 678,734
- 91
- 1,224
- 1,255
-
Thanks, this is what I would expect. I just found out that Tomcat implements one instance of each servlet. Either I was misinformed or some containers really do violate the spec. – Jon Dec 31 '11 at 12:04
-
1Maybe you confused "pool of threads" with "pool of servlet instances". – JB Nizet Dec 31 '11 at 12:07
Servlet containers do have a pool of threads for serving requests, which means there probably will be multiple threads executing servlets code, which means that access to any shared mutable data needs to be properly synchronized.

- 11,872
- 3
- 42
- 49
If the question is how to make servlet single threaded, then one of the approach is to implement the SingleThreadModel interface but this has now been deprecated.
http://docs.oracle.com/javaee/1.4/api/javax/servlet/SingleThreadModel.html

- 2,882
- 9
- 30
- 38