Reputation: 241
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:
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
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.
Upvotes: 2