Skip to content

Instantly share code, notes, and snippets.

@toddlipcon
Created July 23, 2019 23:02
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 toddlipcon/bba4850b0a8ba94d37cfa7bf6bbcb8bc to your computer and use it in GitHub Desktop.
Save toddlipcon/bba4850b0a8ba94d37cfa7bf6bbcb8bc to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.CountDownLatch;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class JettyGracefulShutdown {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
server.setStopTimeout(30000);
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath("/");
contextHandler.addServlet(AsyncServlet.class, "/async").setAsyncSupported(true);
server.setHandler(contextHandler);
StatisticsHandler handler = new StatisticsHandler();
handler.setHandler(server.getHandler());
server.setHandler(handler);
server.start();
System.out.println("Waiting for a request to /async");
latch.await();
System.out.println("Request received. Shutting down");
long start = System.currentTimeMillis();
server.stop();
long duration = System.currentTimeMillis() - start;
System.out.println("Shutdown complete in " + duration + "ms");
}
public static class AsyncServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getAttribute("handled") != null) {
PrintWriter out = response.getWriter();
out.println("Handled!");
out.close();
return;
}
AsyncContext context = request.startAsync();
context.start(() -> {
latch.countDown();
try {
Thread.sleep(10000);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
request.setAttribute("handled", "yes");
context.dispatch();
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment