Singleton.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // SingletonVault - a library to manage the creation and destruction
  17. // of interdependent singletons.
  18. //
  19. // Recommended usage of this class: suppose you have a class
  20. // called MyExpensiveService, and you only want to construct one (ie,
  21. // it's a singleton), but you only want to construct it if it is used.
  22. //
  23. // In your .h file:
  24. // class MyExpensiveService {
  25. // // Caution - may return a null ptr during startup and shutdown.
  26. // static std::shared_ptr<MyExpensiveService> getInstance();
  27. // ....
  28. // };
  29. //
  30. // In your .cpp file:
  31. // namespace { struct PrivateTag {}; }
  32. // static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton;
  33. // std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() {
  34. // return the_singleton.try_get();
  35. // }
  36. //
  37. // Code in other modules can access it via:
  38. //
  39. // auto instance = MyExpensiveService::getInstance();
  40. //
  41. // Advanced usage and notes:
  42. //
  43. // You can also access a singleton instance with
  44. // `Singleton<ObjectType, TagType>::try_get()`. We recommend
  45. // that you prefer the form `the_singleton.try_get()` because it ensures that
  46. // `the_singleton` is used and cannot be garbage-collected during linking: this
  47. // is necessary because the constructor of `the_singleton` is what registers it
  48. // to the SingletonVault.
  49. //
  50. // The singleton will be created on demand. If the constructor for
  51. // MyExpensiveService actually makes use of *another* Singleton, then
  52. // the right thing will happen -- that other singleton will complete
  53. // construction before get() returns. However, in the event of a
  54. // circular dependency, a runtime error will occur.
  55. //
  56. // You can have multiple singletons of the same underlying type, but
  57. // each must be given a unique tag. If no tag is specified a default tag is
  58. // used. We recommend that you use a tag from an anonymous namespace private to
  59. // your implementation file, as this ensures that the singleton is only
  60. // available via your interface and not also through Singleton<T>::try_get()
  61. //
  62. // namespace {
  63. // struct Tag1 {};
  64. // struct Tag2 {};
  65. // folly::Singleton<MyExpensiveService> s_default;
  66. // folly::Singleton<MyExpensiveService, Tag1> s1;
  67. // folly::Singleton<MyExpensiveService, Tag2> s2;
  68. // }
  69. // ...
  70. // MyExpensiveService* svc_default = s_default.get();
  71. // MyExpensiveService* svc1 = s1.get();
  72. // MyExpensiveService* svc2 = s2.get();
  73. //
  74. // By default, the singleton instance is constructed via new and
  75. // deleted via delete, but this is configurable:
  76. //
  77. // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
  78. // destroy); }
  79. //
  80. // Where create and destroy are functions, Singleton<T>::CreateFunc
  81. // Singleton<T>::TeardownFunc.
  82. //
  83. // For example, if you need to pass arguments to your class's constructor:
  84. // class X {
  85. // public:
  86. // X(int a1, std::string a2);
  87. // // ...
  88. // }
  89. // Make your singleton like this:
  90. // folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); });
  91. //
  92. // The above examples detail a situation where an expensive singleton is loaded
  93. // on-demand (thus only if needed). However if there is an expensive singleton
  94. // that will likely be needed, and initialization takes a potentially long time,
  95. // e.g. while initializing, parsing some files, talking to remote services,
  96. // making uses of other singletons, and so on, the initialization of those can
  97. // be scheduled up front, or "eagerly".
  98. //
  99. // In that case the singleton can be declared this way:
  100. //
  101. // namespace {
  102. // auto the_singleton =
  103. // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
  104. // .shouldEagerInit();
  105. // }
  106. //
  107. // This way the singleton's instance is built at program initialization,
  108. // if the program opted-in to that feature by calling "doEagerInit" or
  109. // "doEagerInitVia" during its startup.
  110. //
  111. // What if you need to destroy all of your singletons? Say, some of
  112. // your singletons manage threads, but you need to fork? Or your unit
  113. // test wants to clean up all global state? Then you can call
  114. // SingletonVault::singleton()->destroyInstances(), which invokes the
  115. // TeardownFunc for each singleton, in the reverse order they were
  116. // created. It is your responsibility to ensure your singletons can
  117. // handle cases where the singletons they depend on go away, however.
  118. // Singletons won't be recreated after destroyInstances call. If you
  119. // want to re-enable singleton creation (say after fork was called) you
  120. // should call reenableInstances.
  121. #pragma once
  122. #include <folly/Exception.h>
  123. #include <folly/Executor.h>
  124. #include <folly/Memory.h>
  125. #include <folly/Synchronized.h>
  126. #include <folly/detail/Singleton.h>
  127. #include <folly/detail/StaticSingletonManager.h>
  128. #include <folly/experimental/ReadMostlySharedPtr.h>
  129. #include <folly/hash/Hash.h>
  130. #include <folly/lang/Exception.h>
  131. #include <folly/synchronization/Baton.h>
  132. #include <folly/synchronization/RWSpinLock.h>
  133. #include <algorithm>
  134. #include <atomic>
  135. #include <condition_variable>
  136. #include <functional>
  137. #include <list>
  138. #include <memory>
  139. #include <mutex>
  140. #include <string>
  141. #include <thread>
  142. #include <typeindex>
  143. #include <typeinfo>
  144. #include <unordered_map>
  145. #include <unordered_set>
  146. #include <vector>
  147. #include <glog/logging.h>
  148. // use this guard to handleSingleton breaking change in 3rd party code
  149. #ifndef FOLLY_SINGLETON_TRY_GET
  150. #define FOLLY_SINGLETON_TRY_GET
  151. #endif
  152. namespace folly {
  153. // For actual usage, please see the Singleton<T> class at the bottom
  154. // of this file; that is what you will actually interact with.
  155. // SingletonVault is the class that manages singleton instances. It
  156. // is unaware of the underlying types of singletons, and simply
  157. // manages lifecycles and invokes CreateFunc and TeardownFunc when
  158. // appropriate. In general, you won't need to interact with the
  159. // SingletonVault itself.
  160. //
  161. // A vault goes through a few stages of life:
  162. //
  163. // 1. Registration phase; singletons can be registered:
  164. // a) Strict: no singleton can be created in this stage.
  165. // b) Relaxed: singleton can be created (the default vault is Relaxed).
  166. // 2. registrationComplete() has been called; singletons can no
  167. // longer be registered, but they can be created.
  168. // 3. A vault can return to stage 1 when destroyInstances is called.
  169. //
  170. // In general, you don't need to worry about any of the above; just
  171. // ensure registrationComplete() is called near the top of your main()
  172. // function, otherwise no singletons can be instantiated.
  173. class SingletonVault;
  174. namespace detail {
  175. // A TypeDescriptor is the unique handle for a given singleton. It is
  176. // a combinaiton of the type and of the optional name, and is used as
  177. // a key in unordered_maps.
  178. class TypeDescriptor {
  179. public:
  180. TypeDescriptor(const std::type_info& ti, const std::type_info& tag_ti)
  181. : ti_(ti), tag_ti_(tag_ti) {}
  182. TypeDescriptor(const TypeDescriptor& other)
  183. : ti_(other.ti_), tag_ti_(other.tag_ti_) {}
  184. TypeDescriptor& operator=(const TypeDescriptor& other) {
  185. if (this != &other) {
  186. ti_ = other.ti_;
  187. tag_ti_ = other.tag_ti_;
  188. }
  189. return *this;
  190. }
  191. std::string name() const;
  192. friend class TypeDescriptorHasher;
  193. bool operator==(const TypeDescriptor& other) const {
  194. return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
  195. }
  196. private:
  197. std::type_index ti_;
  198. std::type_index tag_ti_;
  199. };
  200. class TypeDescriptorHasher {
  201. public:
  202. size_t operator()(const TypeDescriptor& ti) const {
  203. return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
  204. }
  205. };
  206. [[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
  207. const TypeDescriptor& type);
  208. [[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
  209. const TypeDescriptor& type);
  210. [[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
  211. const TypeDescriptor& type);
  212. void singletonWarnDestroyInstanceLeak(
  213. const TypeDescriptor& type,
  214. const void* ptr);
  215. [[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
  216. const TypeDescriptor& type);
  217. [[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
  218. const TypeDescriptor& type);
  219. [[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
  220. const TypeDescriptor& type);
  221. void singletonPrintDestructionStackTrace(const TypeDescriptor& type);
  222. [[noreturn]] void singletonThrowNullCreator(const std::type_info& type);
  223. [[noreturn]] void singletonThrowGetInvokedAfterDestruction(
  224. const TypeDescriptor& type);
  225. struct SingletonVaultState {
  226. // The two stages of life for a vault, as mentioned in the class comment.
  227. enum class Type {
  228. Running,
  229. Quiescing,
  230. };
  231. Type state{Type::Running};
  232. bool registrationComplete{false};
  233. // Each singleton in the vault can be in two states: dead
  234. // (registered but never created), living (CreateFunc returned an instance).
  235. void check(
  236. Type expected,
  237. const char* msg = "Unexpected singleton state change") const {
  238. if (expected != state) {
  239. throw_exception<std::logic_error>(msg);
  240. }
  241. }
  242. };
  243. // This interface is used by SingletonVault to interact with SingletonHolders.
  244. // Having a non-template interface allows SingletonVault to keep a list of all
  245. // SingletonHolders.
  246. class SingletonHolderBase {
  247. public:
  248. explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {}
  249. virtual ~SingletonHolderBase() = default;
  250. TypeDescriptor type() const {
  251. return type_;
  252. }
  253. virtual bool hasLiveInstance() = 0;
  254. virtual void createInstance() = 0;
  255. virtual bool creationStarted() = 0;
  256. virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0;
  257. virtual void destroyInstance() = 0;
  258. private:
  259. TypeDescriptor type_;
  260. };
  261. // An actual instance of a singleton, tracking the instance itself,
  262. // its state as described above, and the create and teardown
  263. // functions.
  264. template <typename T>
  265. struct SingletonHolder : public SingletonHolderBase {
  266. public:
  267. typedef std::function<void(T*)> TeardownFunc;
  268. typedef std::function<T*(void)> CreateFunc;
  269. template <typename Tag, typename VaultTag>
  270. inline static SingletonHolder<T>& singleton();
  271. inline T* get();
  272. inline std::weak_ptr<T> get_weak();
  273. inline std::shared_ptr<T> try_get();
  274. inline folly::ReadMostlySharedPtr<T> try_get_fast();
  275. inline void vivify();
  276. void registerSingleton(CreateFunc c, TeardownFunc t);
  277. void registerSingletonMock(CreateFunc c, TeardownFunc t);
  278. bool hasLiveInstance() override;
  279. void createInstance() override;
  280. bool creationStarted() override;
  281. void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override;
  282. void destroyInstance() override;
  283. private:
  284. SingletonHolder(TypeDescriptor type, SingletonVault& vault);
  285. enum class SingletonHolderState {
  286. NotRegistered,
  287. Dead,
  288. Living,
  289. };
  290. SingletonVault& vault_;
  291. // mutex protects the entire entry during construction/destruction
  292. std::mutex mutex_;
  293. // State of the singleton entry. If state is Living, instance_ptr and
  294. // instance_weak can be safely accessed w/o synchronization.
  295. std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
  296. // the thread creating the singleton (only valid while creating an object)
  297. std::atomic<std::thread::id> creating_thread_{};
  298. // The singleton itself and related functions.
  299. // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
  300. // from Dead to Living. Reset when state is changed from Living to Dead.
  301. folly::ReadMostlyMainPtr<T> instance_;
  302. // used to release all ReadMostlyMainPtrs at once
  303. folly::ReadMostlySharedPtr<T> instance_copy_;
  304. // weak_ptr to the singleton instance, set when state is changed from Dead
  305. // to Living. We never write to this object after initialization, so it is
  306. // safe to read it from different threads w/o synchronization if we know
  307. // that state is set to Living
  308. std::weak_ptr<T> instance_weak_;
  309. // Fast equivalent of instance_weak_
  310. folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
  311. // Time we wait on destroy_baton after releasing Singleton shared_ptr.
  312. std::shared_ptr<folly::Baton<>> destroy_baton_;
  313. T* instance_ptr_ = nullptr;
  314. CreateFunc create_ = nullptr;
  315. TeardownFunc teardown_ = nullptr;
  316. std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
  317. SingletonHolder(const SingletonHolder&) = delete;
  318. SingletonHolder& operator=(const SingletonHolder&) = delete;
  319. SingletonHolder& operator=(SingletonHolder&&) = delete;
  320. SingletonHolder(SingletonHolder&&) = delete;
  321. };
  322. } // namespace detail
  323. class SingletonVault {
  324. public:
  325. enum class Type {
  326. Strict, // Singletons can't be created before registrationComplete()
  327. Relaxed, // Singletons can be created before registrationComplete()
  328. };
  329. /**
  330. * Clears all singletons in the given vault at ctor and dtor times.
  331. * Useful for unit-tests that need to clear the world.
  332. *
  333. * This need can arise when a unit-test needs to swap out an object used by a
  334. * singleton for a test-double, but the singleton needing its dependency to be
  335. * swapped has a type or a tag local to some other translation unit and
  336. * unavailable in the current translation unit.
  337. *
  338. * Other, better approaches to this need are "plz 2 refactor" ....
  339. */
  340. struct ScopedExpunger {
  341. SingletonVault* vault;
  342. explicit ScopedExpunger(SingletonVault* v) : vault(v) {
  343. expunge();
  344. }
  345. ~ScopedExpunger() {
  346. expunge();
  347. }
  348. void expunge() {
  349. vault->destroyInstances();
  350. vault->reenableInstances();
  351. }
  352. };
  353. static Type defaultVaultType();
  354. explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {}
  355. // Destructor is only called by unit tests to check destroyInstances.
  356. ~SingletonVault();
  357. typedef std::function<void(void*)> TeardownFunc;
  358. typedef std::function<void*(void)> CreateFunc;
  359. // Ensure that Singleton has not been registered previously and that
  360. // registration is not complete. If validations succeeds,
  361. // register a singleton of a given type with the create and teardown
  362. // functions.
  363. void registerSingleton(detail::SingletonHolderBase* entry);
  364. /**
  365. * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
  366. * is built when `doEagerInit[Via]` is called; see those methods
  367. * for more info.
  368. */
  369. void addEagerInitSingleton(detail::SingletonHolderBase* entry);
  370. // Mark registration is complete; no more singletons can be
  371. // registered at this point.
  372. void registrationComplete();
  373. /**
  374. * Initialize all singletons which were marked as eager-initialized
  375. * (using `shouldEagerInit()`). No return value. Propagates exceptions
  376. * from constructors / create functions, as is the usual case when calling
  377. * for example `Singleton<Foo>::get_weak()`.
  378. */
  379. void doEagerInit();
  380. /**
  381. * Schedule eager singletons' initializations through the given executor.
  382. * If baton ptr is not null, its `post` method is called after all
  383. * early initialization has completed.
  384. *
  385. * If exceptions are thrown during initialization, this method will still
  386. * `post` the baton to indicate completion. The exception will not propagate
  387. * and future attempts to `try_get` or `get_weak` the failed singleton will
  388. * retry initialization.
  389. *
  390. * Sample usage:
  391. *
  392. * folly::IOThreadPoolExecutor executor(max_concurrency_level);
  393. * folly::Baton<> done;
  394. * doEagerInitVia(executor, &done);
  395. * done.wait(); // or 'try_wait_for', etc.
  396. *
  397. */
  398. void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
  399. // Destroy all singletons; when complete, the vault can't create
  400. // singletons once again until reenableInstances() is called.
  401. void destroyInstances();
  402. // Enable re-creating singletons after destroyInstances() was called.
  403. void reenableInstances();
  404. // For testing; how many registered and living singletons we have.
  405. size_t registeredSingletonCount() const {
  406. return singletons_.rlock()->size();
  407. }
  408. /**
  409. * Flips to true if eager initialization was used, and has completed.
  410. * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
  411. */
  412. bool eagerInitComplete() const;
  413. size_t livingSingletonCount() const {
  414. auto singletons = singletons_.rlock();
  415. size_t ret = 0;
  416. for (const auto& p : *singletons) {
  417. if (p.second->hasLiveInstance()) {
  418. ++ret;
  419. }
  420. }
  421. return ret;
  422. }
  423. // A well-known vault; you can actually have others, but this is the
  424. // default.
  425. static SingletonVault* singleton() {
  426. return singleton<>();
  427. }
  428. // Gets singleton vault for any Tag. Non-default tag should be used in unit
  429. // tests only.
  430. template <typename VaultTag = detail::DefaultTag>
  431. static SingletonVault* singleton() {
  432. /* library-local */ static auto vault =
  433. detail::createGlobal<SingletonVault, VaultTag>();
  434. return vault;
  435. }
  436. typedef std::string (*StackTraceGetterPtr)();
  437. static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
  438. /* library-local */ static auto stackTraceGetterPtr = detail::
  439. createGlobal<std::atomic<StackTraceGetterPtr>, SingletonVault>();
  440. return *stackTraceGetterPtr;
  441. }
  442. void setType(Type type) {
  443. type_ = type;
  444. }
  445. private:
  446. template <typename T>
  447. friend struct detail::SingletonHolder;
  448. // This method only matters if registrationComplete() is never called.
  449. // Otherwise destroyInstances is scheduled to be executed atexit.
  450. //
  451. // Initializes static object, which calls destroyInstances on destruction.
  452. // Used to have better deletion ordering with singleton not managed by
  453. // folly::Singleton. The desruction will happen in the following order:
  454. // 1. Singletons, not managed by folly::Singleton, which were created after
  455. // any of the singletons managed by folly::Singleton was requested.
  456. // 2. All singletons managed by folly::Singleton
  457. // 3. Singletons, not managed by folly::Singleton, which were created before
  458. // any of the singletons managed by folly::Singleton was requested.
  459. static void scheduleDestroyInstances();
  460. typedef std::unordered_map<
  461. detail::TypeDescriptor,
  462. detail::SingletonHolderBase*,
  463. detail::TypeDescriptorHasher>
  464. SingletonMap;
  465. // Use SharedMutexSuppressTSAN to suppress noisy lock inversions when building
  466. // with TSAN. If TSAN is not enabled, SharedMutexSuppressTSAN is equivalent
  467. // to a normal SharedMutex.
  468. Synchronized<SingletonMap, SharedMutexSuppressTSAN> singletons_;
  469. Synchronized<
  470. std::unordered_set<detail::SingletonHolderBase*>,
  471. SharedMutexSuppressTSAN>
  472. eagerInitSingletons_;
  473. Synchronized<std::vector<detail::TypeDescriptor>, SharedMutexSuppressTSAN>
  474. creationOrder_;
  475. // Using SharedMutexReadPriority is important here, because we want to make
  476. // sure we don't block nested singleton creation happening concurrently with
  477. // destroyInstances().
  478. Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_;
  479. Type type_;
  480. };
  481. // This is the wrapper class that most users actually interact with.
  482. // It allows for simple access to registering and instantiating
  483. // singletons. Create instances of this class in the global scope of
  484. // type Singleton<T> to register your singleton for later access via
  485. // Singleton<T>::try_get().
  486. template <
  487. typename T,
  488. typename Tag = detail::DefaultTag,
  489. typename VaultTag = detail::DefaultTag /* for testing */>
  490. class Singleton {
  491. public:
  492. typedef std::function<T*(void)> CreateFunc;
  493. typedef std::function<void(T*)> TeardownFunc;
  494. // Generally your program life cycle should be fine with calling
  495. // get() repeatedly rather than saving the reference, and then not
  496. // call get() during process shutdown.
  497. [[deprecated("Replaced by try_get")]] static T* get() {
  498. return getEntry().get();
  499. }
  500. // If, however, you do need to hold a reference to the specific
  501. // singleton, you can try to do so with a weak_ptr. Avoid this when
  502. // possible but the inability to lock the weak pointer can be a
  503. // signal that the vault has been destroyed.
  504. [[deprecated("Replaced by try_get")]] static std::weak_ptr<T> get_weak() {
  505. return getEntry().get_weak();
  506. }
  507. // Preferred alternative to get_weak, it returns shared_ptr that can be
  508. // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
  509. // Avoid holding these shared_ptrs beyond the scope of a function;
  510. // don't put them in member variables, always use try_get() instead
  511. //
  512. // try_get() can return nullptr if the singleton was destroyed, caller is
  513. // responsible for handling nullptr return
  514. static std::shared_ptr<T> try_get() {
  515. return getEntry().try_get();
  516. }
  517. static folly::ReadMostlySharedPtr<T> try_get_fast() {
  518. return getEntry().try_get_fast();
  519. }
  520. // Quickly ensure the instance exists.
  521. static void vivify() {
  522. getEntry().vivify();
  523. }
  524. explicit Singleton(
  525. std::nullptr_t /* _ */ = nullptr,
  526. typename Singleton::TeardownFunc t = nullptr)
  527. : Singleton([]() { return new T; }, std::move(t)) {}
  528. explicit Singleton(
  529. typename Singleton::CreateFunc c,
  530. typename Singleton::TeardownFunc t = nullptr) {
  531. if (c == nullptr) {
  532. detail::singletonThrowNullCreator(typeid(T));
  533. }
  534. auto vault = SingletonVault::singleton<VaultTag>();
  535. getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
  536. vault->registerSingleton(&getEntry());
  537. }
  538. /**
  539. * Should be instantiated as soon as "doEagerInit[Via]" is called.
  540. * Singletons are usually lazy-loaded (built on-demand) but for those which
  541. * are known to be needed, to avoid the potential lag for objects that take
  542. * long to construct during runtime, there is an option to make sure these
  543. * are built up-front.
  544. *
  545. * Use like:
  546. * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
  547. *
  548. * Or alternately, define the singleton as usual, and say
  549. * gFooInstance.shouldEagerInit();
  550. *
  551. * at some point prior to calling registrationComplete().
  552. * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
  553. */
  554. Singleton& shouldEagerInit() {
  555. auto vault = SingletonVault::singleton<VaultTag>();
  556. vault->addEagerInitSingleton(&getEntry());
  557. return *this;
  558. }
  559. /**
  560. * Construct and inject a mock singleton which should be used only from tests.
  561. * Unlike regular singletons which are initialized once per process lifetime,
  562. * mock singletons live for the duration of a test. This means that one
  563. * process running multiple tests can initialize and register the same
  564. * singleton multiple times. This functionality should be used only from tests
  565. * since it relaxes validation and performance in order to be able to perform
  566. * the injection. The returned mock singleton is functionality identical to
  567. * regular singletons.
  568. */
  569. static void make_mock(
  570. std::nullptr_t /* c */ = nullptr,
  571. typename Singleton<T>::TeardownFunc t = nullptr) {
  572. make_mock([]() { return new T; }, t);
  573. }
  574. static void make_mock(
  575. CreateFunc c,
  576. typename Singleton<T>::TeardownFunc t = nullptr) {
  577. if (c == nullptr) {
  578. detail::singletonThrowNullCreator(typeid(T));
  579. }
  580. auto& entry = getEntry();
  581. entry.registerSingletonMock(c, getTeardownFunc(t));
  582. }
  583. private:
  584. inline static detail::SingletonHolder<T>& getEntry() {
  585. return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
  586. }
  587. // Construct TeardownFunc.
  588. static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
  589. TeardownFunc t) {
  590. if (t == nullptr) {
  591. return [](T* v) { delete v; };
  592. } else {
  593. return t;
  594. }
  595. }
  596. };
  597. template <typename T, typename Tag = detail::DefaultTag>
  598. class LeakySingleton {
  599. public:
  600. using CreateFunc = std::function<T*()>;
  601. LeakySingleton() : LeakySingleton([] { return new T(); }) {}
  602. explicit LeakySingleton(CreateFunc createFunc) {
  603. auto& entry = entryInstance();
  604. if (entry.state != State::NotRegistered) {
  605. detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_);
  606. }
  607. entry.createFunc = createFunc;
  608. entry.state = State::Dead;
  609. }
  610. static T& get() {
  611. return instance();
  612. }
  613. static void make_mock(std::nullptr_t /* c */ = nullptr) {
  614. make_mock([]() { return new T; });
  615. }
  616. static void make_mock(CreateFunc createFunc) {
  617. if (createFunc == nullptr) {
  618. detail::singletonThrowNullCreator(typeid(T));
  619. }
  620. auto& entry = entryInstance();
  621. if (entry.ptr) {
  622. // Make sure existing pointer doesn't get reported as a leak by LSAN.
  623. entry.leakedPtrs.push_back(std::exchange(entry.ptr, nullptr));
  624. }
  625. entry.createFunc = createFunc;
  626. entry.state = State::Dead;
  627. }
  628. private:
  629. enum class State { NotRegistered, Dead, Living };
  630. struct Entry {
  631. Entry() {}
  632. Entry(const Entry&) = delete;
  633. Entry& operator=(const Entry&) = delete;
  634. std::atomic<State> state{State::NotRegistered};
  635. T* ptr{nullptr};
  636. CreateFunc createFunc;
  637. std::mutex mutex;
  638. detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
  639. std::list<T*> leakedPtrs;
  640. };
  641. static Entry& entryInstance() {
  642. /* library-local */ static auto entry = detail::createGlobal<Entry, Tag>();
  643. return *entry;
  644. }
  645. static T& instance() {
  646. auto& entry = entryInstance();
  647. if (UNLIKELY(entry.state != State::Living)) {
  648. createInstance();
  649. }
  650. return *entry.ptr;
  651. }
  652. static void createInstance() {
  653. auto& entry = entryInstance();
  654. std::lock_guard<std::mutex> lg(entry.mutex);
  655. if (entry.state == State::Living) {
  656. return;
  657. }
  658. if (entry.state == State::NotRegistered) {
  659. detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_);
  660. }
  661. entry.ptr = entry.createFunc();
  662. entry.state = State::Living;
  663. }
  664. };
  665. } // namespace folly
  666. #include <folly/Singleton-inl.h>