views:

423

answers:

6

I am working on a web application in Java which gets data from servlets via AJAX calls.

This application features several page elements which get new data from the server at fairly rapid intervals.

With a lot of users, the demand on the server has a potential to get fairly high, so I am curious:

Which approach offers the best performance:

Many servlets (one for each type of data request)?

Or:

a single servlet that can handle all of the requests?

+8  A: 

There is no performance reason to have more than one servlet. In a web application, only a single instance of a servlet class is instantitated, no matter how many requests. Requests are not serialized, they are handled concurrently, hence the need for your servlet to be thread safe.

Tony BenBrahim
Thanks, I was never quite clear about what exactly happened at the low level for servlets.
TM
+2  A: 

The struts framework uses one servlet for everything in your app. Your stuff plugs into that one servlet. If it works for them, it will probably work for you.

S.Lott
A: 

Like Tony said, there really isn't a reason to use more than one servlet, unless you need to break up a complex Java Servlet class or perhaps implement an intercepting filter.

Eric Wendelin
1. You should rarely, if ever, add attributes to ServletContext.2. Can you back this up: "Multiple servlets is definitely the way to go for raw speed"? it is simply not correct,If you need to synchronize on something, you will have to synchronize whether you have 1 or 100 servlets
Tony BenBrahim
1. Just saying ServletContext is not thread-safe and nothing about good practice. 2. You're absolutely right on that, brain fart on my part and I'll change my answer. I was thinking that we might avoid thread blocking in some small way with multiple servlets. My fault.
Eric Wendelin
+1  A: 

One possible reason to have multiple services is that if you need to expand to multiple servers to handle the load in the future, it is easier to move a seperate service to it's own server than to do it "behind the scenes" if everything is comming out of one service.

That being said, there is extra maintinence overhead if you have multiple servlets, so it is a matter of balancing future flexibility with lower maintainability.

cdeszaq
unfortunately, the question asked about Ajax request, so the server must be the same as the where the page was loaded from. The acknowledged way to do what you suggest is with a load balancer in front of multiple servers, all serving the same content (i.e. all have the same servlets)
Tony BenBrahim
+1  A: 

There is as such no performance enhancements in case you use multiple servlets since for each servlet request is handled in a separate thread, provided it is not single threaded.

But keeping modularity and separation of code, you can have multiple servlets.

Nrj
A: 
anjanb