views:

35

answers:

1

We have two singleton objects (declared via in(Scopes.SINGLETON)) in Guice that each uses the other in its constructor. Guice's way to implement this is with proxies - it initializes the object at first with a proxy to the other object, and only when that object is needed it is resolved.

When running this code from several threads, we get the following exception:

java.lang.IllegalStateException: This is a proxy used to support
circular references involving constructors. The object we're proxying is not
constructed yet. Please wait until after injection has completed to use this
object.
    at
com.google.inject.internal.ConstructionContext$DelegatingInvocationHandler.invoke(ConstructionContext.java:100)

I assume this is a bug in Guice, because we aren't doing anything out of the ordinary. One workaround we found is initializing the singletons early using .asEagerSingleton(), but this is not very convenient, for testing for example.

Is this a known issue? Reported an issue with Google Guice, reproduces with a standalone test.

Any other suggestions/workaround?

+1  A: 

Did you try injecting a Provider<T> in each constructor instead of the actual instances?

If you don't need the other instance in the code of constructor, then just store the Provider to a final field, and use this field later on (by calling get()).

jfpoilpret
Yeah, I already tried this workaround and it works. Now the problem is detecting all the cases in my code where I have circular dependency and replacing them with a provider :(
ripper234
BTW, note that the trunk version of Guice has this patch to disable circular proxies: http://code.google.com/p/google-guice/source/detail?r=1151
ripper234