Skip to content

Releasable Singletons

Stéphane Nicolas edited this page Jul 16, 2019 · 4 revisions

Releasable Singletons are singletons that can be released, i.e garbage collected, when the application is under memory pressure. A new instance will be recreated and will be shared again as a singleton if an injection requests it.

On Android, application can react to memory pressure in various ways. Toothpick can release releasable singletons to free up some memory.

To declare a singleton as releasable, one can:

  • either use a binding (.singleton().releasable() or .providesSingleton().providesRelesable())
  • or use annotations (@Singleton @Releasable or @ProvidesSingleton @ProvidesReleasable).

To release all singletons of a given scope, call Toothpick.release(scopeName). All singletons of this scope and children scopes will be released. Typically, this is called on the root scope.

Implications

Ideally, releasable singletons should:

  • either be completely stateless
  • or manage / persist their states on disk so that they can always be released and recreated on demand.

In both cases, it is the entire responsibility of the developer to make sure that no references of releasable singletons prevent their garbage collection. If it would happen, the scope would contain 2 instances of the singleton.

Generally speaking, releasable singletons are very convenient for stateless classes. They allow to gain speed by recycling an instance of such a class, and preventing the creation of similar objects, while still allowing to release the RAM that they are using.

Links