users@jersey.java.net

[Jersey] ServiceLocator.getService() returning stale results

From: cowwoc <cowwoc_at_bbs.darktech.org>
Date: Mon, 12 May 2014 18:20:42 -0400

Hi,

I am attempting to dynamically bind a value "Foo" to Jersey's
@RequestScoped scope. When someone invokes getFoo() I invoke the
following code:

         Foo result = serviceLocator.getService(Foo.class);
         if (result == null)
         {
             result = new Foo();
             ServiceLocatorUtilities.bind(serviceLocator,
                 new RequestScopedBinder<>(Foo.class, result));
         }
         return result;

where RequestScopedBinder invokes:

bindFactory(new ValueFactory()).to(Foo.class).in(RequestScoped.class);

where ValueFactory is a factory that returns the value passed into
RequestScopedBinder.

In short, when getFoo() is invoked, I ask ServiceLocator if it has a
value. If not, I construct one and inject the instance into the
@RequestScoped scope.

Unfortunately, sometimes serviceLocator.getService(Foo.class) returns
stale values from previous request scopes. Digging into the code I see
it gets this value from an internal "cache" before even consulting the
scope. I'm guessing it's treating the factory value as @RequestScoped
but not the factory itself.

Is there a way for me to mark the factory as @RequestScoped?

Thanks,
Gili