folly Singleton: "eager" option to initialize upfront
authorSteve O'Brien <steveo@fb.com>
Thu, 17 Sep 2015 13:30:23 +0000 (06:30 -0700)
committerfacebook-github-bot-9 <folly-bot@fb.com>
Thu, 17 Sep 2015 14:20:19 +0000 (07:20 -0700)
commite4527fb5d04f5fec823bd6a2402b620a6e1a64e3
tree70c4f8bf81b2cb9be5e21f9266fbd5fbcc814a5c
parent2171293fe73e3b08e8aff2af70758e2c5dcdf4d7
folly Singleton: "eager" option to initialize upfront

Summary: Instead of the default lazy-loading behavior (still the default) some singletons might need to get initialized at startup time.  This would be for singletons which take a long time for the instance's constructor to run, e.g. expensive initialization by reading some large dataset, talking to an outside service, and so on.

Provides a way for singletons to opt-in to this, and get populated at the time  `registrationComplete()` is called, instead of lazily.

Some notes about the way I implemented here, mainly, why I did this as a "builder-pattern" kind of thing and not some other way.  I could probably be convinced to do otherwise. :)

* Changing the constructor: the constructor's already slightly fiddly with the two optional -- well, one optional construct function, and another optional-but-only-if-construct-provided, destruct function.  Didn't want to pile more into the ctor.
* New superclass called `EagerLoadedSingleton`; just didn't want to add more classes, esp. if it's just to add one more option.
* Method like `void setEagerLoad()` that makes this eager-load; not sure where one would write the `shouldEagerLoad()` call, probably in some central initialization spot in `main()`, but all the maintenance would have to go there.  I like that it's "attached" to the singleton being defined.  (Though you can still do this.)  Bonus #2; the rule that builds the cpp containing "main" doesn't need to import this dependency and the cpp doesn't have to include Singleton just to do this eager-load call, nor the header for the type itself.
* Omitting this altogether and just saying `folly::Singleton<Foo>::get_weak()` to "ping" the singleton and bring into existence: see last point.  Still might need to have the file containing this initialization decorum include/link against Foo, as well as have one place to maintain the list of things to load up-front.

Reviewed By: @meyering

Differential Revision: D2449081
folly/Singleton-inl.h
folly/Singleton.h
folly/test/SingletonTest.cpp