Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet 3.0 asynchronous

What's the diffrence between servlet 3.0 asynchronous feature against:

Оld servlet implementation:

doGet(request,response) {
Thread t = new Thread(new Runnable()
     void run(){
        // heavy processing
        response.write(result)
     }
}
t.start();

In servlet 3.0 if I waste a thread to do heavy processing - I earn one more thread in the container, but I waste it in heavy processing... :(

Could somebody help?

like image 950
moty Avatar asked Sep 28 '10 07:09

moty


People also ask

What is asynchronous servlet?

In short, an asynchronous servlet enables an application to process incoming requests in an asynchronous fashion: A given HTTP worker thread handles an incoming request and then passes the request to another background thread which in turn will be responsible for processing the request and send the response back to the ...

Does the servlet API allow asynchronous processing of requests?

If a servlet or a filter reaches a potentially blocking operation when processing a request, it can assign the operation to an asynchronous execution context and return the thread associated with the request immediately to the container without generating a response.

What is AsyncContext?

An AsyncContext is created and initialized by a call to ServletRequest#startAsync() or ServletRequest#startAsync(ServletRequest, ServletResponse) . Repeated invocations of these methods will return the same AsyncContext instance, reinitialized as appropriate.

What is asynchronous method in Java?

An Asynchronous call does not block the program from the code execution. When the call returns from the event, the call returns back to the callback function. So in the context of Java, we have to Create a new thread and invoke the callback method inside that thread.


1 Answers

This won't work. Once your doGet method ends, the response is complete and sent back to the client. Your thread may or may not still be running, but it can't change the response any longer.

What the new async feature in Servlet 3.0 does, is that it allows you to free the request thread for processing another request. What happens is the following:

RequestThread:  |-- doGet() { startAsync() }  // Thread free to do something else
WorkerThread:                 |-- do heavy processing --|
OtherThread:                                            |-- send response --|

The important thing is that once RequestThread has started asynchronous processing via a call to startAsync(...), it is free to do something else. It can accept new requests, for example. This improves throughput.

like image 191
Ronald Wildenberg Avatar answered Oct 13 '22 06:10

Ronald Wildenberg