Note that there are some explanatory texts on larger screens.

plurals
  1. POGuava : setting the default Executor for ListenableFuture callbacks and listeners
    text
    copied!<p>Our application has a number of services that implement <code>ListenableFuture</code>-based APIs, to the tune of:</p> <pre><code>public interface MyService { ListenableFuture&lt;Thing&gt; getMyThing(); ListenableFuture&lt;?&gt; putMyThing(Thing thing); } </code></pre> <p>As our domain model is not at all thread-safe, we run most of our code, except for the aforementioned services, on a well-known single-thread <code>Executor</code>. I think it would be nice if the services could guarantee that any listener added to the <code>Future</code>s they produce will be called on that <code>Executor</code>.</p> <p>Of course, I could very well enforce this in the services' clients, by calling <code>ListenableFuture.addListener</code>, <code>Futures.addCallback</code> or <code>Futures.transform</code> with the appropriate <code>Executor</code> argument but what I'm aiming at is precisely reducing the complexity and possibility of errors in the client code, so I would like the listener calls to happen on the well-known <code>Executor</code> when those methods are called without passing an <code>Executor</code> argument.</p> <p>So, for now I've been implementing the services' methods this way:</p> <pre><code>class MyServiceImpl { private Executor executor; /* the "main" executor */ public ListenableFuture&lt;Thing&gt; getMyThing() { ListenableFuture&lt;Thing&gt; future = ...; /* actual service call */ return Futures.transform(future, Functions.&lt;Thing&gt;identity(), executor ); } } </code></pre> <p>First, does this even work? From the Guava source, it seems that it does, but I would be glad for some kind of confirmation, and I'm having a bit of a hard time thinking about unit testing this.</p> <p>Moreover, I'm a bit worried about the usefulness/cost ratio of the whole "Service calls back on specified thread (by default)" pattern. Does anyone have experience with something like this? Are there any hidden pitfalls in this approach?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload