Class SingletonScope

java.lang.Object
com.google.inject.internal.SingletonScope
All Implemented Interfaces:
Scope

public class SingletonScope extends Object implements Scope
One instance per 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.

  1. Guice has never truly expected to be used in multi threading environment with many Injectors working alongside each other. There is almost no code with Guice that propagates state between threads. And Singleton scope is The exception.
  2. Guice supports circular dependencies and thus manages proxy objects. There is no interface that allows user defined Scopes to create proxies, it is expected to be done by Guice. Singleton scope needs to be able to detect circular dependencies spanning several threads, therefore Singleton scope needs to be able to create these proxies.
  3. To make things worse, Guice has a very tricky definition for a binding resolution when Injectors are in in a parent/child relationship. And Scope does not have access to this information by design, the only real action that Scope can do is to call or not to call a creator.
  4. There is no readily available code in Guice that can detect a potential deadlock, and no code for handling dependency cycles spanning several threads. This is significantly harder as all the dependencies in a thread at runtime can be represented with a list, where in a multi threaded environment we have more complex dependency trees.
  5. Guice has a pretty strong contract regarding Garbage Collection, which often prevents us from linking objects directly. So simple domain specific code can not be written and intermediary id objects need to be managed.
  6. Guice is relatively fast and we should not make things worse. We're trying our best to optimize synchronization for speed and memory. Happy path should be almost as fast as in a single threaded solution and should not take much more memory.
  7. Error message generation in Guice was not meant to be used like this and to work around its APIs we need a lot of code. Additional complexity comes from inherent data races as message is only generated when failure occurs on proxy object generation. Things get ugly pretty fast.
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    Allows us to detect when circular proxies are necessary.
    private static final Object
    A sentinel value representing null.
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    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
    A short but useful description of this scope.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Field Details

    • NULL

      private static final Object NULL
      A sentinel value representing null.
    • cycleDetectingLockFactory

      private static final CycleDetectingLock.CycleDetectingLockFactory<Key<?>> cycleDetectingLockFactory
      Allows us to detect when circular proxies are necessary. It's only used during singleton instance initialization, after initialization direct access through volatile field is used.

      NB: Factory uses Keys 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.

  • Constructor Details

    • SingletonScope

      public SingletonScope()
  • Method Details

    • scope

      public <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
      Specified by:
      scope in interface Scope
      Parameters:
      key - binding key
      creator - locates an instance when one doesn't already exist in this scope.
      Returns:
      a new provider which only delegates to the given unscoped provider when an instance of the requested object doesn't already exist in this scope
      See Also:
    • toString

      public String toString()
      Description copied from interface: Scope
      A short but useful description of this scope. For comparison, the standard scopes that ship with guice use the descriptions "Scopes.SINGLETON", "ServletScopes.SESSION" and "ServletScopes.REQUEST".
      Specified by:
      toString in interface Scope
      Overrides:
      toString in class Object