2

My application is built on top of Guice and runs scheduled jobs (cron4j), which are showing some issues related to inherently @Singleton instances.

The appropriate solution to my problem seems to have Scope that would be applicable for each job run, instead of the Singleton one. It would be similar to the Request scope, but in this different scenario.

I've read the docs for Custom Scopes, but it isn't clear to me on how a given dependency would know on how to request an specific scoped instance from guice.

Example:

public class MyJob {
    /* Knows its "run id", which could be used for the scoping mechanism */

    @Inject private Dependency dep;
    public void run() { ... }
}

public class Dependency {
    /* Technically does not know the "run id" from the job */

    @Inject @Named("jobRunScope") private InnerDependency innerDep;
}

I appreciate any guidance.

everton
  • 7,579
  • 2
  • 29
  • 42

1 Answers1

1

If you look at the source for RequestScoped, you'll see that it uses a ThreadLocal to store a special Context map, holding all of the key-object pairs for the current request.

If your jobs run in a single thread, you could use a similar strategy to store scoped singletons.

Another option would be to create a new Injector instance for each job.

jkinkead
  • 4,101
  • 21
  • 33