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?
问题:
回答1:
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.
回答2:
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.
回答3:
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