Phate
Phate

Reputation: 6612

Is it bad to create a thread pool into servlets?

I have an httpservlet which has to make multiple connections to different services in order to provide an answer. These requests are very little and the call to servlet itself is done by ajax, moreover what I am creating is just a web interface for a program which will be used by few users at the same time.

Now, I though about instantiating a threadpool into the servlet and make it execute my tasks, a join will make sure that each thread finishes before continuing.

I read, anyway, that spamming threads inside a servlet is a bad practice. But making these connections parallel sounds the best way to handle my problem.

So, what do you suggest?What would the best way be?

Upvotes: 1

Views: 585

Answers (1)

Daniel
Daniel

Reputation: 4549

It's not a "bad idea", but it needs to be done with care. Depending on the load your server gets, the amount of memory and CPU you have available, etc... it may indeed be the best way. We do it all the time at my work.

A good place to start is by using a thread pool. Java 1.5+ has a great class for this called ExecutorService

You can create a single pool that is shared for all Servlet requests, or one pool per request.

Having a shared pool gives you an absolute upper bound of these worker threads. Having a new thread per request lets keeps interaction between servlet requests down (one request can't hog all the threads).

An alternative to consider for your use case though, there are ways to service multiple HTTP calls with a single thread, depending on what library you use. They would use nio behind the scenes. I don't know the names of any off the top of my head though.

Upvotes: 2

Related Questions