【发布时间】:2013-09-03 19:20:29
【问题描述】:
我担心 Guice 以及它的单例是否会遵守我可能会尝试设置的线程限制:
public class CacheModule extends AbstractModule {
@Override
protected void configure() {
// WidgetCache.class is located inside a 3rd party JAR that I
// don't have the ability to modify.
WidgetCache widgetCache = new WidgetCache(...lots of params);
// Guice will reuse the same WidgetCache instance over and over across
// multiple calls to Injector#getInstance(WidgetCache.class);
bind(WidgetCache.class).toInstance(widgetCache);
}
}
// CacheAdaptor is the "root" of my dependency tree. All other objects
// are created from it.
public class CacheAdaptor {
private CacheModule bootstrapper = new CacheModule();
private WidgetCache widgetCache;
public CacheAdaptor() {
super();
Injector injector = Guice.createInjector(bootstrapper);
setWidgetCache(injector.getInstance(WidgetCache.class));
}
// ...etc.
}
如您所见,每当我们创建CacheAdaptor 的新实例时,CacheModule 将用于引导它下面的整个依赖关系树。
如果从多个线程内部调用 new CacheAdaptor(); 会发生什么?
例如:线程#1 通过它的无参数构造函数创建一个新的CacheAdaptor,线程#2 做同样的事情。 Guice 会为每个线程的 CacheAdaptor 提供完全相同的 WidgetCache 实例,还是 Guice 会为每个线程提供 2 个不同的实例? 即使 toInstance(...) 应该返回相同的单例实例,我我希望 - 因为模块是在 2 个不同的线程中创建的 - 每个 CacheAdaptor 将收到不同的 WidgetCache 实例。
提前致谢!
【问题讨论】:
-
你说的是单例,但我没看到
-
@PhilippSander -
bind(WidgetCache.class).toInstance(widgetCache)创建一个单例WidgetCache实例,然后无论客户端请求多少次都重用它(通过Injector#getInstance(WidgetCache.class)。 -
你刚刚回答了你的问题......
-
再次感谢@PhilippSander - 但是您是否阅读过我的问题? 这个问题与 Guice 跨多个线程的行为有关。我知道,对于单线程应用程序,
bind(WidgetCache.class).toInstance(widgetCache)创建了一个单例 - 但是该单例是否受线程限制?WidgetCache非常可行线程#1中的模块获得的实例将不同于线程#2中获得的实例。 -
是的,我做到了——它实际上出现在上面的 bold 中,如下所示:“如果从多个线程内部调用 new CacheAdaptor(); 会发生什么? b>”。我一直很感谢@PhilippSander 的所有意见,但如果你不知道这个问题的答案,我会请你继续回答另一个问题。
标签: java dependency-injection singleton guice