Servlet Only One Instance In Container?
the answer is depend on.
You can let the servlet implement SingleThreadModel
to get the container to create a pool of multiple instances of the same servlet class. The maximum pool size depends on the container used, on Tomcat for example, this is 20. But, a big but, this interface is deprecated since Servlet 2.4! We should actually be writing servlets in a thread-safe manner, without assigning request- and/or session scoped data as an instance variable of the servlet. This way it's safe to use a single servlet instance across multiple threads (read: across multiple HTTP requests).
Servlet container instantiates single instance for each servlet declaration. That means, that you can have multiple servlet instances, but you need to declare the servlet as many times as many instances you want/need. This also brings the question of how servlets would be invoked ... they would need to be mapped to different paths.
Another way you can do this is to make a pool of handlers which your single servlet may call.
how to make them thread-safe: that depends on what exactly you want to do in those handlers. It's hard to tell you in general.
If you're asking about thread-safe pool, you can use Apache Commons Pool library, or some BlockingQueue (e.g. LinkedBlockingQueue) in Java: queue may contain your handlers. Servlet willtake()
first handler, use it, and put()
it back after it's done. (This is just an example of course, there are many ways to implement pool).
But ... make sure you really need design like this, maybe your requirements can be satisfied by something simpler? (If your goal is to limit number of concurrent requests handled at the same time, maybe it's enough to just limit number of HTTP worker threads in your container? Or if that's not enough, you can use a limiting filter?)
Further Read:
Related:
see also
java servlet instantiation and session variables
conclusion:
Only one instance if you do not implement singlethreadmodel.but, this interface is deprecated since Servlet 2.4!
posted on 2012-07-16 17:27 malaikuangren 阅读(320) 评论(0) 编辑 收藏 举报