The answer is depend on.
You can let the servlet implementSinglethreadmodelTo 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 bigBut, This interface is deprecated since servlet 2.4! We shoshould 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 processing SS multiple threads (read: Processing SS 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 frequently times as your instances you want/need. this also brings the question of how servlets wocould be invoked... they wowould 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 in your handlers. servlet willTake ()First handler, use it, andPut ()It back after it's done. (This is just an example of course, there are always 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:
- The servlet InterfaceOn onjava
Related:
Javax. servlet. servletAPI
- Servlet instance poolOn Java ranch
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!