Skip to content

Instantly share code, notes, and snippets.

@maxtomassi
Last active September 18, 2016 08:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxtomassi/7134908 to your computer and use it in GitHub Desktop.
Save maxtomassi/7134908 to your computer and use it in GitHub Desktop.
public void listenableFutureWithCallbackExample() {
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(NUMBER_OF_THREADS));
Callable<String> asyncTask = new Callable<String>() {
@Override
public String call() throws Exception {
return computeResult();
}
};
ListenableFuture<String> listenableFuture = executor.submit(asyncTask);
Futures.addCallback(listenableFuture, new FutureCallback<String>() {
public void onSuccess(String result) {
doMoreWithTheResultImmediately(result);
}
public void onFailure(Throwable thrown) {
handleFailure(thrown);
}
});
doSomethingElse();
try {
String result = listenableFuture.get();
useResult(result);
} catch (ExecutionException e) {
log.error("Task failed", e);
} catch (InterruptedException e) {
log.warn("Task interrupted", e);
}
executor.shutdown();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment