Injector Thread Safety

2,276 views
Skip to first unread message

Pablo Ruggia

unread,
Dec 14, 2008, 10:32:01 AM12/14/08
to google...@googlegroups.com
Hi !
It's not clear reading the documentation if the initialization of singletons is thread safe or not.
I mean, if I have a singleton that is lazy initialized, for example, using a Provider, does it get synchronized so only one instance is being created at a time.
If it's not a singleton, does it synchronize something anyway?
Which is my responsibility as a library client in what regards to thread safety.
Thanks !

PS: great job, I'm new guice user coming from Spring and I'm already loving it !

Robbie Vanbrabant

unread,
Dec 14, 2008, 11:11:55 AM12/14/08
to google...@googlegroups.com
On Sun, Dec 14, 2008 at 4:32 PM, Pablo Ruggia <pru...@gmail.com> wrote:
I mean, if I have a singleton that is lazy initialized, for example, using a Provider, does it get synchronized so only one instance is being created at a time.

Yes, Guice's singleton scope uses DCL with a global lock on Injector.class (which is rather conservative).

If it's not a singleton, does it synchronize something anyway?

This is typically up to the scope. Probably HTTP session scope synchronizes on the session, HTTP request probably does not synchronize because it uses ThreadLocal.

Which is my responsibility as a library client in what regards to thread safety.

Once Guice returns from createInjector, thread safety is up to you. So if you have a provider that manages its own lazyy reference to something, it's up to you to make sure it is thread safe. The same goes for everything that is mutable. Singletons that keep mutable state need to be properly synchronized / volatile'd.

Cheers
Robbie

Gavin Bong

unread,
Dec 17, 2008, 3:30:58 AM12/17/08
to google-guice
On the same topic, if I save my Injector (returned from
createInjector) inside a local variable in my servlet, and call it on
every doGet() / doPost(), would that be ok ?

I'm calling Injector.getInstance( .. ) for every invocation of the
servlet.

Regards,

Gavin

Bob Lee

unread,
Dec 17, 2008, 12:04:30 PM12/17/08
to google...@googlegroups.com
That's just fine.
Reply all
Reply to author
Forward
0 new messages