Jon
Jon

Reputation: 101

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?

Upvotes: 3

Views: 1501

Answers (3)

JB Nizet
JB Nizet

Reputation: 691685

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.

Upvotes: 3

Jyotirup
Jyotirup

Reputation: 2920

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

Upvotes: 1

milan
milan

Reputation: 12412

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.

Upvotes: 1

Related Questions