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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With