Search code examples
javaguava

How responsive is Guava's ListenableFuture


How does ListenableFuture check whether the result is ready so that the registered listeners can be executed immediately or as fast as possible?

Does ListenableFuture busy waiting by calling isDone() (I suppose that is a stupid solution)? Or does it have internal tasks to periodically call get(long timeout, TimeUnit unit) with some fine tuned timeout value? If it is waking up periodically to call get(long timeout, TimeUnit unit), is there a parameter for the user to tune this behavior because I would love my listener to be executed as soon as the result becomes available.

Any doc or soure code references would be appreciated to understand this further.


Solution

  • It's instant.

    There isn't a separate thread busy waiting. All instances of ListenableFuture returned by Guava or the ListeningExecutorService that it provides are subclasses of AbstractFuture and call set when they have a result. set itself calls a method called complete, which submits the listeners on the ListenableFuture to their associated Executor.

    That said, there's no guarantee that the Executor attached to the listener will run the listener job immediately. That's up to you to make sure of, or if you want it to run synchronously and your listener is fast and you're okay blocking on it, you can use MoreExecutors.directExecutor().