public class SingletonScope extends java.lang.Object implements Scope
Injector
. Also see @
Singleton
.
Introduction from the author: Implementation of this class seems unreasonably complicated at the first sight. I fully agree with you, that the beast below is very complex and it's hard to reason on how does it work or not. Still I want to assure you that hundreds(?) of hours were thrown into making this code simple, while still maintaining Singleton contract.
Anyway, why is it so complex? Singleton scope does not seem to be that unique.
scope(Key, Provider)
,
CycleDetectingLock
Modifier and Type | Field and Description |
---|---|
private static CycleDetectingLock.CycleDetectingLockFactory<Key<?>> |
cycleDetectingLockFactory
Allows us to detect when circular proxies are necessary.
|
private static java.lang.Object |
NULL
A sentinel value representing null.
|
Constructor and Description |
---|
SingletonScope() |
Modifier and Type | Method and Description |
---|---|
<T> Provider<T> |
scope(Key<T> key,
Provider<T> creator)
Provides singleton scope with the following properties:
creates no more than one instance per Key as a creator is used no more than once
result is cached and returned quickly on subsequent calls
exception in a creator is not treated as instance creation and is not cached
creates singletons in parallel whenever possible
waits for dependent singletons to be created even across threads and when dependencies
are shared as long as no circular dependencies are detected
returns circular proxy only when circular dependencies are detected
aside from that, blocking synchronization is only used for proxy creation and
initialization
|
java.lang.String |
toString()
A short but useful description of this scope.
|
private static final java.lang.Object NULL
private static final CycleDetectingLock.CycleDetectingLockFactory<Key<?>> cycleDetectingLockFactory
NB: Factory uses Key
s as a user locks ids, different injectors can share them.
Cycles are detected properly as cycle detection does not rely on user locks ids, but error
message generated could be less than ideal.
public <T> Provider<T> scope(Key<T> key, Provider<T> creator)
scope
in interface Scope
key
- binding keycreator
- locates an instance when one doesn't already exist in this scope.CycleDetectingLock.CycleDetectingLockFactory
public java.lang.String toString()
Scope
"Scopes.SINGLETON"
, "ServletScopes.SESSION"
and
"ServletScopes.REQUEST"
.