Guice is creating thousands of instances of classes

76 views
Skip to first unread message

Brian Pontarelli

unread,
Sep 10, 2019, 8:26:52 PM9/10/19
to google...@googlegroups.com
Hi everyone,

Not sure how active this group is anymore, but I’m having a very strange problem that I can seem to get to the bottom of. It could actually be the normal behavior of Guice, but I’m guessing it isn’t.

Here’s an example:

Let’s say I have 3 services named ServiceA, ServiceB and ServiceC and then a Controller. The dependencies look like this:

Controller -> ServiceA
Controller -> ServiceB
Controller -> ServiceC
ServiceA -> ServiceB
ServiceA -> ServiceC
ServiceB -> ServiceC

Essentially, ServiceC is being used everywhere. When I create an instance of the Controller, Guice is creating 3 or more instances of ServiceC. In my real-world case, Guice is creating 500+ or more instances of a single service for each request to the application. It seems like Guice should only be creating 1 instance of ServiceC since it is a leaf node in the graph and the graph is being constructed from a single location (Controller).

A bit of additional detail, we are using multi-binders in some places and the classes being bound into the collections do use a number of services.

Anyone have this issue and figure out how to solve it?

Thanks,
— Brian

Fred Faber

unread,
Sep 10, 2019, 8:31:31 PM9/10/19
to google...@googlegroups.com
By default Guice will create a new instance of each dependency. If you want to canonicalize on using the same instance on different parts of an object graph, scope your binding. You'll want to be sure your implementation is stateless or otherwise safe to share among different call points (and possibly threads).

See here for more details: https://github.com/google/guice/wiki/Scopes 

--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-guice/1BA470AA-6E4D-4471-A7AA-C03ED80C7FC2%40pontarelli.com.

Brian Pontarelli

unread,
Sep 10, 2019, 8:49:37 PM9/10/19
to google...@googlegroups.com
Thanks Fred. That makes sense and I will look into Scopes.

Brian Pontarelli
CleanSpeak & FusionAuth
cleanspeak.com & fusionauth.io | LinkedIn | Twitter

Sent from my iPhone
Reply all
Reply to author
Forward
0 new messages