Skip to content

Instantly share code, notes, and snippets.

@maxant
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxant/23f01fd9a5529095cf27 to your computer and use it in GitHub Desktop.
Save maxant/23f01fd9a5529095cf27 to your computer and use it in GitHub Desktop.
@WebServlet(urlPatterns = { "/AsyncServlet2" }, asyncSupported = true)
public class AsyncServlet2 extends HttpServlet {
@EJB private Service3 service;
protected void doGet(HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final PrintWriter pw = response.getWriter();
pw.write("<html><body>Started publishing with thread " + Thread.currentThread().getId() + "<br>");
response.flushBuffer(); // send back to the browser NOW
CompletableFuture<String> cf = new CompletableFuture<>();
service.foo(cf);
// since we need to keep the response open, we need to start an async context
final AsyncContext ctx = request.startAsync(request, response);
cf.whenCompleteAsync((s, t)->{
try {
if(t!=null) throw t;
pw.write("written in the future using thread " + Thread.currentThread().getId()
+ "... service response is:");
pw.write(s);
pw.write("</body></html>");
response.flushBuffer();
ctx.complete(); // all done, free resources
} catch (Throwable t2) {
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment