user3876178
user3876178

Reputation: 241

JSP Servlet Multithreading Qustion

I have a Servlet which gets a request from a client, then the Servlet gathers data from 5 different Servers via http request/response (every Server needs 1sec to respond) and sends the data back to the client.

The Problem is that it is too long when the Client has to wait 6 seconds for the response. So the 5 requests to the 5 Servers must be sent at the same time.

Ideas:

  1. Multithreading in the Servlet, like in a normal Java Application.
  2. An own Servlet for every Server(request), so that 1 main servlet says to the 5 Gather Servlets "get the data xy" and the gather Servlets send the data to the main servlet and the main servlet back to the client.

The Problem i fear about is, that a thread/servlet gets the response from an another request because its the same time and same ip.

How to solve this? Thanks!

Upvotes: 0

Views: 799

Answers (1)

Braj
Braj

Reputation: 46881

Multithreading in the Servlet

You can use ServletRequest#startAsync() method that puts this request into asynchronous mode, and initializes its AsyncContext with the original (unwrapped) ServletRequest and ServletResponse objects.

Read more about Servlet 3 0 final-spec - Section 2.3.3.3 - Asynchronous processing where it is explained in detail.

AsyncContext is a standard way defined in Servlet 3.0 specification to handle HTTP requests asynchronously.


Read more about Executors.newFixedThreadPool() that creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

Please have a look at ExecutorService to read more about it along with sample code.

Read more...

Upvotes: 2

Related Questions