AsyncHandler.java 981 B

12345678910111213141516171819202122232425262728293031323334
  1. package hello;
  2. import static hello.Helper.sendException;
  3. import io.undertow.server.HttpHandler;
  4. import io.undertow.server.HttpServerExchange;
  5. import io.undertow.util.SameThreadExecutor;
  6. import java.util.Objects;
  7. /**
  8. * An HTTP handler that <em>does not</em> end the exchange when the call stack
  9. * of its {@link HttpHandler#handleRequest(HttpServerExchange)} method returns.
  10. * The handler must ensure that every exchange is ended through other means.
  11. */
  12. final class AsyncHandler implements HttpHandler {
  13. private final HttpHandler handler;
  14. AsyncHandler(HttpHandler handler) {
  15. this.handler = Objects.requireNonNull(handler);
  16. }
  17. @Override
  18. public void handleRequest(HttpServerExchange exchange) {
  19. Runnable asyncTask =
  20. () -> {
  21. try {
  22. handler.handleRequest(exchange);
  23. } catch (Exception e) {
  24. sendException(exchange, e);
  25. }
  26. };
  27. exchange.dispatch(SameThreadExecutor.INSTANCE, asyncTask);
  28. }
  29. }