This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have a servlet, that calls a web service, and gets data to populate the servlet response.
I also don't want to wait too long.
Can I just spawn a new thread and call the web service? If this is not recommended, what is a better way ?
I would not spawn the thread in the servlet itself
A better approach would be to spawn off a daemon thread before the servlet action. Have it just wait for work. In the servlet, you can send a "request" to your daemon to do whatever you want. Just create a small Message class with needed information, and call a method in the daemon to process it.
You will need a semaphore to block the servlet's thread until it gets a response from the daemon or times out.
The very purpose of application/web servers is to alleviate the problems of threads and related stuff from developers as the container takes care of them. If you start a thread on your own in a container environment and it goes to hung status then you have one less thread in the container. In a multi user environment this may lead to exhausting all the resources (threads). Hence it is not recommended to start the thread in containers.
With reference to your issue for waiting the ideal situation is to use ajax with timed intervals.