[undertow-dev] how to use futures with undertow?

Sascha Sadat-Guscheh kid at bitkid.com
Thu Dec 10 07:22:38 EST 2015


Hi!

We want to use undertow as the http server for our application. Our current API is based on futures (java8 completable futures). My question is how do i combine futures with the concept of handlers. My rather naive implementation would be something like that.

class MyHandler implements HttpHandler {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getRequestReceiver().receiveFullString((exchange1, message) -> {
                CompletableFuture<Response> responseFuture = doTheWork(message);
                exchange1.dispatch();
                responseFuture.whenCompleteAsync((response, throwable) -> {
                     exchange1.getResponseSender().send(response);
                });
            });
        }
}

does this look reasonable? responseFuture.whenCompleteAsync() can be passed an Executor. Should i use an Executor from the HttpServerExchange for that? actually i tried to, but it’s always null. Another way would be:

class MyHandler implements HttpHandler {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getRequestReceiver().receiveFullString((exchange1, message) -> {
                CompletableFuture<Response> responseFuture = doTheWork(message);
                exchange1.dispatch(() -> {
                        exchange1.getResponseSender().send(responseFuture.get());
                });
            });
        }
}

What’s the correct way to do it?

Thanks, Sascha 


More information about the undertow-dev mailing list