jeudi 12 mars 2015

Asynchronous property in Servlet 3.0 testing query



I have implemented Asynchronous property in Servlet 3.0 using below tutorial.


http://ift.tt/1C9Bq5N


After implenting a runnable class at backend, I have observed that the 2 threads are created and one ends up in asunchronous manner and other does backend processing. I was able to implement successfully the mentioned Asynchronus property. In the runnable class, I have kept a sleep of 25 seconds and I have tried using outStream.println(Calendar.getInstance().getTimeInMillis()) in the servlet class, I have observed a deviation.The time value which is printed in println is the time when the request started but the outStream is printed on the URL hit page after 25 seconds. I just want to understand when print was framed within servlet (based on timestamp I came to this analysis), why is it printed in servlet URL hit page after worker class sleep time.



@WebServlet(name="asyncServlet",value = {"/async"},asyncSupported = true)
public class AsyncServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
protected void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
servletoutputstream out = response.getoutputstream();
final AsyncContext ctx = req.startAsync();
ctx.addListener(new AsyncListener() {
@Override
public void onTimeout(AsyncEvent arg0) throws IOException {
System.out.println("onTimeout...");
}

@Override
public void onStartAsync(AsyncEvent arg0) throws IOException {
System.out.println("onStartAsync...");
}

@Override
public void onError(AsyncEvent arg0) throws IOException {
System.out.println("onError...");
}

@Override
public void onComplete(AsyncEvent arg0) throws IOException {
System.out.println("onComplete...");
}
});
ctx.start(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread.sleep(1000);

} catch InterruptedException e) {
e.printStackTrace();
}

ctx.complete();
}
});
out.write("Got the request"+calendar.getinstance().gettimeinmillis());
out.close();
}
}


Here I am printing out, the time captured in out string is before the sleep time yet it is printed in after sleep time.


I have tried with printwriter, yet same output is observed. Is there any way to print the response before sleep time using above code.




Aucun commentaire:

Enregistrer un commentaire