Skip to content

Instantly share code, notes, and snippets.

@RichardHightower
Created April 8, 2016 17:35
Show Gist options
  • Save RichardHightower/7420dd953e86e0b46956564026448194 to your computer and use it in GitHub Desktop.
Save RichardHightower/7420dd953e86e0b46956564026448194 to your computer and use it in GitHub Desktop.
Simple Example using Guava Futures

Simplest example.

    public static void main(String... args) throws Exception{


        ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

        Callable<String> asyncTask = () -> {
            Thread.sleep(1000);
            return "called";
        };

        ListenableFuture<String> listenableFuture = executor.submit(asyncTask);

        Futures.addCallback(listenableFuture, new FutureCallback<String>() {
            public void onSuccess(String result) {
                System.out.println(result);
            }

            public void onFailure(Throwable thrown) {
               thrown.printStackTrace();
            }
        });
        Thread.sleep(1000);


        try {
            String result = listenableFuture.get();
            System.out.println(result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        Thread.sleep(1000);
        executor.shutdown();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment