It seems that all Guice's out-of-the-box Scope implementations are inherently Thread-based (or ignore Threads entirely):
Scopes.SINGLETON
and Scopes.NO_SCOPE
ignore Threads and are the edge cases: global scope and no scope.
ServletScopes.REQUEST
and ServletScopes.SESSION
ultimately depend on retrieving scoped objects from a ThreadLocal<Context>
. The retrieved Context
holds a reference to the HttpServletRequest
that holds a reference to the scoped objects stored as named attributes (where name is derived from com.google.inject.Key
).
Class SimpleScope
from the custom scope Guice wiki also provides a per-Thread implementation using a ThreadLocal<Map<Key<?>, Object>>
member variable.
With that preamble, my question is this: how does one go about creating a non-Thread-based Scope? It seems that something that I can use to look up a Map<Key<?>, Object>
is missing, as the only things passed in to Scope.scope()
are a Key<T>
and a Provider<T>
.
Thanks in advance for your time.
It's a bit unclear what you want - you don't want scopes that are based on threads, and you don't want scopes that ignore threads.
But yes, scopes are intended to manage the lifecycle of an object and say when an instance should be reused. So really you're asking "what are the other possibilities for re-using an instance beyond 'always use the same instance', 'never use the same instance', and 'use an instance depending on the execution environment of the current thread'?"
Here's what comes to mind:
InheritableThreadLocal
, not a plain ThreadLocal
.Scope
and a threadpool-based ExecutorService
that work togehter so that instances are shared between a thread and jobs it submits for background execution.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With