Originally posted by dinram:
Hi All,
In servlets,if we do not want "n" number of threads to access simultaneously the servlet instance, we can go in for SingleThreadModel interface so that only a single thread runs at any one time.
Now,instead of going for SingleThreadModel Interface, I can also use the keyword "synchronised".Even synchronised does the same job.Am I right?
If I am right, then what is the difference between using SingleThreadModel and synchronised?
Regards,
Dinesh.G
I would recommend using the SingleThreadModel interface to synchronize your servlets if that's really what you want. If you use the synchronized keyword, all requests are serialized through EXACTLY ONE instance of your servlet class. However, if your servlet implements the SingleThreadModel interface, the servlet container is free to use a pool of instancese of your servlet class to service the requests. See the servlet specification section SRV.2.3.3.1 Multithreading Issues...
A servlet container may send concurrent requests through the service method of
the servlet. To handle the requests the developer of the servlet must make adequate
provisions for concurrent processing with multiple threads in the service method.
An alternative for the developer is to implement the SingleThreadModel
interface which requires the container to guarantee that there is only one request
thread at a time in the service method. A servlet container may satisfy this
requirement by serializing requests on a servlet, or by maintaining a pool of servlet
instances. If the servlet is part of a web application that has been marked as distributable,
the container may maintain a pool of servlet instances in each VM that
the application is distributed across.
For servlets not implementing the SingleThreadModel interface, if the
service method (or methods such as doGet or doPost which are dispatched to the
service method of the HttpServlet abstract class) has been defined with the
synchronized keyword, the servlet container cannot use the instance pool
approach, but must serialize requests through it. It is strongly recommended that
developers not synchronize the service method (or methods dispatched to it) in
these circumstances because of detrimental effects on performance.