Last active
September 18, 2016 08:02
-
-
Save maxtomassi/7134908 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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