我们的应用程序有许多实现ListenableFuture
基于 API 的服务,以调整:
public interface MyService {
ListenableFuture<Thing> getMyThing();
ListenableFuture<?> putMyThing(Thing thing);
}
由于我们的域模型根本不是线程安全的,因此我们在众所周知的单线程上运行大部分代码,除了上述服务Executor
。我认为,如果服务能够保证添加到Future
它们生成的 s 的任何侦听器都会被调用,那就太好了Executor
。
当然,我可以通过调用或使用适当的参数在服务的客户端中很好地执行此操作ListenableFuture.addListener
,但我的目标是精确地降低客户端代码中的复杂性和错误的可能性,所以我希望监听器当调用这些方法而不传递参数时,调用将在众所周知的情况下发生。Futures.addCallback
Futures.transform
Executor
Executor
Executor
所以,现在我一直在以这种方式实现服务的方法:
class MyServiceImpl {
private Executor executor; /* the "main" executor */
public ListenableFuture<Thing> getMyThing() {
ListenableFuture<Thing> future = ...; /* actual service call */
return Futures.transform(future, Functions.<Thing>identity(), executor );
}
}
首先,这是否有效?从 Guava 源来看,似乎确实如此,但我会很高兴得到某种确认,而且我在考虑对此进行单元测试时有点困难。
此外,我有点担心整个“服务在指定线程上回调(默认情况下)”模式的有用性/成本比。有没有人有这样的经验?这种方法有什么隐藏的陷阱吗?