On Thu, Jan 15, 2009 at 3:24 PM, Rick <[email protected]> wrote: > > > On Wed, Jan 14, 2009 at 10:04 PM, Dhanji R. Prasanna <[email protected]>wrote: > >> >> It's not the enum that's the problem, it's the lazy creation of the >> injector: >> >> private Injector getInjector() { >> if (injector == null) { >> injector = Guice.createInjector(getModules()); >> } >> return injector; >> } >> >> This can lead to multiple injectors being created concurrently, and worse: >> to partially created injectors being visible from other threads. >> >> >> > > In my case that I posted as an enum I wasn't actually doing the above null > check and was initializing it right away on one line which I thought was > safe since everything I seem to be reading (but I'm still looking) seems to > at least imply that in a multi-threaded environment any instance > declarations in the enum wouldn't be hit so that it's safe in an enum to do: > > public enum ServiceFactory { > INSTANCE; > > Injector injector = Guice.createInjector(getModules()); > > public <T> T getService(Class<T> clz) { > return injector.getInstance(clz); > } > > private Collection<Module> getModules() { > // > return modules; > } > > } > > Wouldn't all the instance initializers fire before any other thread had > access to the enum? > > similar to how (from what I rember) an eagerly loaded singleton with > statics is thread-safe as well...? > > private static final Foo instance = new Foo(); > private Foo() {} > public static Foo getInstance() { > return instance; > } >
This example is safe. Your lazy-singleton (further up in the thread) was not, since the injector gets created on first USE rather than on class initialization. Dhanji. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "google-guice" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/google-guice?hl=en -~----------~----~----~----~------~----~------~--~---
