About Tomasz Nurkiewicz

Java EE developer, Scala enthusiast. Enjoying data analysis and visualization. Strongly believes in the power of testing and automation.

ListenableFuture in Guava

ListenableFuture in Guava is an attempt to define consistent API for Future objects to register completion callbacks. With the ability to add callback when Future completes, we can asynchronously and effectively respond to incoming events. If your application is highly concurrent with lots of future objects, I strongly recommend using ListenableFuture whenever you can. Technically ListenableFuture extends Future interface by adding simple:
 
 
 
 
 

void addListener(Runnable listener, Executor executor)

method. That’s it. If you get a hold of ListenableFuture you can register Runnable to be executed immediately when future in question completes. You must also supply Executor (ExecutorService extends it) that will be used to execute your listener – so that long-running listeners do not occupy your worker threads.

Let’s put that into action. We will start by refactoring our first example of web crawler to use ListenableFuture. Fortunately in case of thread pools it’s just a matter of wrapping them using MoreExecutors.listeningDecorator():

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

for (final URL siteUrl : topSites) {
    final ListenableFuture<String> future = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return IOUtils.toString(siteUrl, StandardCharsets.UTF_8);
        }
    });

    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                final String contents = future.get();
                //...process web site contents
            } catch (InterruptedException e) {
                log.error("Interrupted", e);
            } catch (ExecutionException e) {
                log.error("Exception in task", e.getCause());
            }
        }
    }, MoreExecutors.sameThreadExecutor());
}

There are several interesting observations to make. First of all notice how ListeningExecutorService wraps existing Executor. This is similar to ExecutorCompletionService approach. Later on we register custom Runnable to be notified when each and every task finishes. Secondly notice how ugly error handling becomes: we have to handle InterruptedException (which should technically never happen as Future is already resolved and get() will never throw it) and ExecutionException. We haven’t covered that yet, but Future<T> must somehow handle exceptions occurring during asynchronous computation. Such exceptions are wrapped in ExecutionException (thus the getCause() invocation during logging) thrown from get().

Finally notice MoreExecutors.sameThreadExecutor() being used. It’s a handy abstraction which you can use every time some API wants to use an Executor/ExecutorService (presumably thread pool) while you are fine with using current thread. This is especially useful during unit testing – even if your production code uses asynchronous tasks, during tests you can run everything from the same thread.

No matter how handy it is, whole code seems a bit cluttered. Fortunately there is a simple utility method in fantastic Futures class:

Futures.addCallback(future, new FutureCallback<String>() {
    @Override
    public void onSuccess(String contents) {
        //...process web site contents
    }

    @Override
    public void onFailure(Throwable throwable) {
        log.error("Exception in task", throwable);
    }
});

FutureCallback is a much simpler abstraction to work with, resolves future and does exception handling for you. Also you can still supply custom thread pool for listeners if you want. If you are stuck with some legacy API that still returns Future you may try JdkFutureAdapters.listenInPoolThread() which is an adapter converting plain Future<V> to ListenableFuture<V>. But keep in mind that once you start using addListener(), each such adapter will require one thread exclusively to work so this solution doesn’t scale at all and you should avoid it.

Future<String> future = //...
ListenableFuture<String> listenableFuture =
        JdkFutureAdapters.listenInPoolThread(future);

Once we understand the basics we can dive deeply into biggest strength of listening futures: transformations and chaining. This is advanced stuff, you have been warned.
 

Reference: ListenableFuture in Guava from our JCG partner Tomasz Nurkiewicz at the NoBlogDefFound blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


four − = 1



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books