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