Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet synchronization when multiple instances

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?

like image 957
Jon Avatar asked Jun 30 '26 09:06

Jon


2 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.

like image 143
JB Nizet Avatar answered Jul 02 '26 21:07

JB Nizet


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.

like image 41
milan Avatar answered Jul 02 '26 22:07

milan