adamSpline
adamSpline

Reputation: 483

thread started from Servlet - is it always bad idea?

I have a servlet which does the following:

  1. Gets a set of data from a webservice
  2. Gets a set of data from the local database.
  3. Merges the two sets and returns the results.

Actually little of this is done within the servlet code itself, but the servlet calls Java classes which do the above.

Since most of the time is spent waiting for both the webservice and database, I am considering performing the two concurrently: put the webserivce call in a thread, get the data from the Database, and then waiting until the webservice is done before continuing. This seems like it should work fine, but I often hear that launching threads from servlets is a bad idea? I am having trouble seeing how this situation would lead to problems. Any help would be great (using tomcat 6 on linux). Thanks!

Upvotes: 0

Views: 457

Answers (3)

Op De Cirkel
Op De Cirkel

Reputation: 29503

Number of threads at a moment the system can support is limited resource. Also, creating a thread is expensive operation. Because of that the modern servlet containers do not create new thread for every request, but maintain pool of threads. A thread from the pool is assigned to incoming request. If all threads are busy the request is placed in queue or new thread is created (depending on the strategy the servlet container uses).

So, creating threads would certainly work (from functional perspective), but if you have many requests coming, your server will start choking. You can use similar strategy as the servlet container uses. Java already offers framework for this kind of tasks. Take a look in the javadocs for Executor and the related classes.

Upvotes: 0

Suraj Chandran
Suraj Chandran

Reputation: 24801

I dont see anything wrong with it and have often seen threads being started from a servlet itself. You use-case is good justification for starting threads within servlet.

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

Every time a request hits server, the container allocates or creates a new thread for handling the request, for every request, everytime service() method is called in its own stack, then service() method calls the doGet OR doPost depending on the Http request. Now its perfectly fine to use thread which in confined within the scope of doGet or doPost.

Upvotes: 0

Related Questions