Java Reference
In-Depth Information
LISTING 9-3: (continued)
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
// Code not shown for brevity
}
});
new Thread() {
@Override
public void run() {
asyncContext.complete();
}
}.start();
res.getWriter().write("Results:");
//Read data from database
data = "Queried data…";
//sleep thread for some time…
}
}
This servlet prints Results: and later prints retrieved data from the database, which is a simple string
in this scenario. You need to initialize a separate thread. AsyncListener's onComplete method is
executed only when the execution completes. Several other life cycle methods exist in the AsyncListener:
onStartAsync —executes when the asynchronous context starts
onTimeOut —executes only if a timeout occurs
onError —executes only if an error is received
The Servlet 3.1 specii cation provided an easier way to implement asynchronous servlets by
using managed thread pools and the executor service. The example in Listing 9‐4 uses a
ManagedThreadFactory to create a new thread.
LISTING 9‐4: An example that uses ManagedThreadFactory
package com.devchronicles.asynchronous;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(urlPatterns="/async", asyncSupported=true)
public class AsyncServlet extends HttpServlet {
@Resource
private ManagedThreadFactory factory;
@Override
Search WWH ::




Custom Search