How would you provide return within X seconds semantics for a servlet request?
My client wants my servlet to be able to return results within X seconds if there is somethi开发者_如何学编程ng to return, else return zt X seconds with a message like "sorry could not return within specified time"
This is really a synchronos call to a servlet with a timeout. Is there an established pattern for this sort of behavior ?
What would be the ideal way to do this ?
The request handler thread creates a BlockingQueue called myQueue and gives it to a worker thread which will place its result in the queue when it is finished. Then the handler thread calls "myQueue.poll(X, TimeUnit.SECONDS)
" and returns the serialized result if it gets one or your "timeout" error if it gets null instead (meaning the "poll" call timed out). Here is an example of how it might look:
// Servlet handler method.
BlockingQueue<MyResponse> queue = new ArrayBlockingQueue<MyResponse>();
Thread worker = new Thread(new MyResponseGenerator(queue));
worker.start();
MyResponse response = queue.poll(10, TimeUnit.SECONDS);
if (response == null) {
worker.interrupt();
// Send "timeout" message.
} else {
// Send serialized response.
}
Note that thread management in general (but especially in a servlet container) is full of pitfalls, so you should become very familiar with the servlet specification and behavior of your particular servlet container before using this pattern in a production system.
Using a ThreadPool is another option to consider but will add another layer of complexity.
精彩评论