Thursday, October 18, 2012

Getting unchecked result of Future with Guava

If you like Java Executor Framework as much as I do (and hate checked exceptions as much as I do), then you probably start to swear each time you need to handle all these annoying checked exceptions of Future#get.
Future<MyMessage> response =
  camelProducerTemplate.asyncRequestBody(
    "http://veryslow.com/esb/service",
    "request", MyMessage.class);
...
// Do something else waiting for the HTTP response.
...
try {
  handleResponse(response.get());
} catch (InterruptedException e) {
  throw new RuntimeException(e);
} catch (ExecutionException e) {
  throw new RuntimeException(e);
}
Handling checked exceptions of Future is especially annoying, as Executor Framework is widely used when implementing popular Request-Reply pattern in messaging systems.

Fortunately Guava's Futures utility provides glue code for handling Future#get exceptions. This extremely useful method is called getUnchecked.
import static com.google.common.util.concurrent.Futures.getUnchecked;
...
Future<MyMessage> response =
  camelProducerTemplate.asyncRequestBody(
    "http://veryslow.com/esb/service",
    "request", MyMessage.class);
...
// Do something else waiting for the HTTP response.
...
handleResponse(getUnchecked(response));

Thank you Google.

2 comments: