Register singleton's destruction using std::atexit
[folly.git] / folly / Singleton.h
1 /*
2  * Copyright 2017-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
122 #pragma once
123
124 #include <folly/Exception.h>
125 #include <folly/Executor.h>
126 #include <folly/Memory.h>
127 #include <folly/Synchronized.h>
128 #include <folly/detail/StaticSingletonManager.h>
129 #include <folly/experimental/ReadMostlySharedPtr.h>
130 #include <folly/hash/Hash.h>
131 #include <folly/synchronization/Baton.h>
132 #include <folly/synchronization/RWSpinLock.h>
133
134 #include <algorithm>
135 #include <atomic>
136 #include <condition_variable>
137 #include <functional>
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
148 #include <glog/logging.h>
149
150 // use this guard to handleSingleton breaking change in 3rd party code
151 #ifndef FOLLY_SINGLETON_TRY_GET
152 #define FOLLY_SINGLETON_TRY_GET
153 #endif
154
155 namespace folly {
156
157 // For actual usage, please see the Singleton<T> class at the bottom
158 // of this file; that is what you will actually interact with.
159
160 // SingletonVault is the class that manages singleton instances.  It
161 // is unaware of the underlying types of singletons, and simply
162 // manages lifecycles and invokes CreateFunc and TeardownFunc when
163 // appropriate.  In general, you won't need to interact with the
164 // SingletonVault itself.
165 //
166 // A vault goes through a few stages of life:
167 //
168 //   1. Registration phase; singletons can be registered:
169 //      a) Strict: no singleton can be created in this stage.
170 //      b) Relaxed: singleton can be created (the default vault is Relaxed).
171 //   2. registrationComplete() has been called; singletons can no
172 //      longer be registered, but they can be created.
173 //   3. A vault can return to stage 1 when destroyInstances is called.
174 //
175 // In general, you don't need to worry about any of the above; just
176 // ensure registrationComplete() is called near the top of your main()
177 // function, otherwise no singletons can be instantiated.
178
179 class SingletonVault;
180
181 namespace detail {
182
183 struct DefaultTag {};
184
185 // A TypeDescriptor is the unique handle for a given singleton.  It is
186 // a combinaiton of the type and of the optional name, and is used as
187 // a key in unordered_maps.
188 class TypeDescriptor {
189  public:
190   TypeDescriptor(const std::type_info& ti,
191                  const std::type_info& tag_ti)
192       : ti_(ti), tag_ti_(tag_ti) {
193   }
194
195   TypeDescriptor(const TypeDescriptor& other)
196       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
197   }
198
199   TypeDescriptor& operator=(const TypeDescriptor& other) {
200     if (this != &other) {
201       ti_ = other.ti_;
202       tag_ti_ = other.tag_ti_;
203     }
204
205     return *this;
206   }
207
208   std::string name() const;
209
210   friend class TypeDescriptorHasher;
211
212   bool operator==(const TypeDescriptor& other) const {
213     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
214   }
215
216  private:
217   std::type_index ti_;
218   std::type_index tag_ti_;
219 };
220
221 class TypeDescriptorHasher {
222  public:
223   size_t operator()(const TypeDescriptor& ti) const {
224     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
225   }
226 };
227
228 [[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
229     const TypeDescriptor& type);
230
231 [[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
232     const TypeDescriptor& type);
233
234 [[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
235     const TypeDescriptor& type);
236
237 void singletonWarnDestroyInstanceLeak(
238     const TypeDescriptor& type,
239     const void* ptr);
240
241 [[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
242     const TypeDescriptor& type);
243
244 [[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
245     const TypeDescriptor& type);
246
247 [[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
248     const TypeDescriptor& type);
249
250 void singletonPrintDestructionStackTrace(const TypeDescriptor& type);
251
252 [[noreturn]] void singletonThrowNullCreator(const std::type_info& type);
253
254 [[noreturn]] void singletonThrowGetInvokedAfterDestruction(
255     const TypeDescriptor& type);
256
257 struct SingletonVaultState {
258   // The two stages of life for a vault, as mentioned in the class comment.
259   enum class Type {
260     Running,
261     Quiescing,
262   };
263
264   Type state{Type::Running};
265   bool registrationComplete{false};
266
267   // Each singleton in the vault can be in two states: dead
268   // (registered but never created), living (CreateFunc returned an instance).
269
270   void check(
271       Type expected,
272       const char* msg = "Unexpected singleton state change") const {
273     if (expected != state) {
274       throwUnexpectedState(msg);
275     }
276   }
277
278   [[noreturn]] static void throwUnexpectedState(const char* msg);
279 };
280
281 // This interface is used by SingletonVault to interact with SingletonHolders.
282 // Having a non-template interface allows SingletonVault to keep a list of all
283 // SingletonHolders.
284 class SingletonHolderBase {
285  public:
286   explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {}
287   virtual ~SingletonHolderBase() = default;
288
289   TypeDescriptor type() const {
290     return type_;
291   }
292   virtual bool hasLiveInstance() = 0;
293   virtual void createInstance() = 0;
294   virtual bool creationStarted() = 0;
295   virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0;
296   virtual void destroyInstance() = 0;
297
298  private:
299   TypeDescriptor type_;
300 };
301
302 // An actual instance of a singleton, tracking the instance itself,
303 // its state as described above, and the create and teardown
304 // functions.
305 template <typename T>
306 struct SingletonHolder : public SingletonHolderBase {
307  public:
308   typedef std::function<void(T*)> TeardownFunc;
309   typedef std::function<T*(void)> CreateFunc;
310
311   template <typename Tag, typename VaultTag>
312   inline static SingletonHolder<T>& singleton();
313
314   inline T* get();
315   inline std::weak_ptr<T> get_weak();
316   inline std::shared_ptr<T> try_get();
317   inline folly::ReadMostlySharedPtr<T> try_get_fast();
318
319   void registerSingleton(CreateFunc c, TeardownFunc t);
320   void registerSingletonMock(CreateFunc c, TeardownFunc t);
321   bool hasLiveInstance() override;
322   void createInstance() override;
323   bool creationStarted() override;
324   void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override;
325   void destroyInstance() override;
326
327  private:
328   SingletonHolder(TypeDescriptor type, SingletonVault& vault);
329
330   enum class SingletonHolderState {
331     NotRegistered,
332     Dead,
333     Living,
334   };
335
336   SingletonVault& vault_;
337
338   // mutex protects the entire entry during construction/destruction
339   std::mutex mutex_;
340
341   // State of the singleton entry. If state is Living, instance_ptr and
342   // instance_weak can be safely accessed w/o synchronization.
343   std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
344
345   // the thread creating the singleton (only valid while creating an object)
346   std::atomic<std::thread::id> creating_thread_;
347
348   // The singleton itself and related functions.
349
350   // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
351   // from Dead to Living. Reset when state is changed from Living to Dead.
352   folly::ReadMostlyMainPtr<T> instance_;
353   // used to release all ReadMostlyMainPtrs at once
354   folly::ReadMostlySharedPtr<T> instance_copy_;
355   // weak_ptr to the singleton instance, set when state is changed from Dead
356   // to Living. We never write to this object after initialization, so it is
357   // safe to read it from different threads w/o synchronization if we know
358   // that state is set to Living
359   std::weak_ptr<T> instance_weak_;
360   // Fast equivalent of instance_weak_
361   folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
362   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
363   std::shared_ptr<folly::Baton<>> destroy_baton_;
364   T* instance_ptr_ = nullptr;
365   CreateFunc create_ = nullptr;
366   TeardownFunc teardown_ = nullptr;
367
368   std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
369
370   SingletonHolder(const SingletonHolder&) = delete;
371   SingletonHolder& operator=(const SingletonHolder&) = delete;
372   SingletonHolder& operator=(SingletonHolder&&) = delete;
373   SingletonHolder(SingletonHolder&&) = delete;
374 };
375
376 } // namespace detail
377
378 class SingletonVault {
379  public:
380   enum class Type {
381     Strict, // Singletons can't be created before registrationComplete()
382     Relaxed, // Singletons can be created before registrationComplete()
383   };
384
385   /**
386    * Clears all singletons in the given vault at ctor and dtor times.
387    * Useful for unit-tests that need to clear the world.
388    *
389    * This need can arise when a unit-test needs to swap out an object used by a
390    * singleton for a test-double, but the singleton needing its dependency to be
391    * swapped has a type or a tag local to some other translation unit and
392    * unavailable in the current translation unit.
393    *
394    * Other, better approaches to this need are "plz 2 refactor" ....
395    */
396   struct ScopedExpunger {
397     SingletonVault* vault;
398     explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
399     ~ScopedExpunger() { expunge(); }
400     void expunge() {
401       vault->destroyInstances();
402       vault->reenableInstances();
403     }
404   };
405
406   static Type defaultVaultType();
407
408   explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {}
409
410   // Destructor is only called by unit tests to check destroyInstances.
411   ~SingletonVault();
412
413   typedef std::function<void(void*)> TeardownFunc;
414   typedef std::function<void*(void)> CreateFunc;
415
416   // Ensure that Singleton has not been registered previously and that
417   // registration is not complete. If validations succeeds,
418   // register a singleton of a given type with the create and teardown
419   // functions.
420   void registerSingleton(detail::SingletonHolderBase* entry);
421
422   /**
423    * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
424    * is built when `doEagerInit[Via]` is called; see those methods
425    * for more info.
426    */
427   void addEagerInitSingleton(detail::SingletonHolderBase* entry);
428
429   // Mark registration is complete; no more singletons can be
430   // registered at this point.
431   void registrationComplete();
432
433   /**
434    * Initialize all singletons which were marked as eager-initialized
435    * (using `shouldEagerInit()`).  No return value.  Propagates exceptions
436    * from constructors / create functions, as is the usual case when calling
437    * for example `Singleton<Foo>::get_weak()`.
438    */
439   void doEagerInit();
440
441   /**
442    * Schedule eager singletons' initializations through the given executor.
443    * If baton ptr is not null, its `post` method is called after all
444    * early initialization has completed.
445    *
446    * If exceptions are thrown during initialization, this method will still
447    * `post` the baton to indicate completion.  The exception will not propagate
448    * and future attempts to `try_get` or `get_weak` the failed singleton will
449    * retry initialization.
450    *
451    * Sample usage:
452    *
453    *   folly::IOThreadPoolExecutor executor(max_concurrency_level);
454    *   folly::Baton<> done;
455    *   doEagerInitVia(executor, &done);
456    *   done.wait();  // or 'try_wait_for', etc.
457    *
458    */
459   void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
460
461   // Destroy all singletons; when complete, the vault can't create
462   // singletons once again until reenableInstances() is called.
463   void destroyInstances();
464
465   // Enable re-creating singletons after destroyInstances() was called.
466   void reenableInstances();
467
468   // For testing; how many registered and living singletons we have.
469   size_t registeredSingletonCount() const {
470     return singletons_.rlock()->size();
471   }
472
473   /**
474    * Flips to true if eager initialization was used, and has completed.
475    * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
476    */
477   bool eagerInitComplete() const;
478
479   size_t livingSingletonCount() const {
480     auto singletons = singletons_.rlock();
481
482     size_t ret = 0;
483     for (const auto& p : *singletons) {
484       if (p.second->hasLiveInstance()) {
485         ++ret;
486       }
487     }
488
489     return ret;
490   }
491
492   // A well-known vault; you can actually have others, but this is the
493   // default.
494   static SingletonVault* singleton() {
495     return singleton<>();
496   }
497
498   // Gets singleton vault for any Tag. Non-default tag should be used in unit
499   // tests only.
500   template <typename VaultTag = detail::DefaultTag>
501   static SingletonVault* singleton() {
502     /* library-local */ static auto vault =
503         detail::createGlobal<SingletonVault, VaultTag>();
504     return vault;
505   }
506
507   typedef std::string(*StackTraceGetterPtr)();
508
509   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
510     /* library-local */ static auto stackTraceGetterPtr = detail::
511         createGlobal<std::atomic<StackTraceGetterPtr>, SingletonVault>();
512     return *stackTraceGetterPtr;
513   }
514
515   void setType(Type type) {
516     type_ = type;
517   }
518
519  private:
520   template <typename T>
521   friend struct detail::SingletonHolder;
522
523   // This method only matters if registrationComplete() is never called.
524   // Otherwise destroyInstances is scheduled to be executed atexit.
525   //
526   // Initializes static object, which calls destroyInstances on destruction.
527   // Used to have better deletion ordering with singleton not managed by
528   // folly::Singleton. The desruction will happen in the following order:
529   // 1. Singletons, not managed by folly::Singleton, which were created after
530   //    any of the singletons managed by folly::Singleton was requested.
531   // 2. All singletons managed by folly::Singleton
532   // 3. Singletons, not managed by folly::Singleton, which were created before
533   //    any of the singletons managed by folly::Singleton was requested.
534   static void scheduleDestroyInstances();
535
536   typedef std::unordered_map<detail::TypeDescriptor,
537                              detail::SingletonHolderBase*,
538                              detail::TypeDescriptorHasher> SingletonMap;
539   Synchronized<SingletonMap> singletons_;
540   Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
541       eagerInitSingletons_;
542   Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
543
544   // Using SharedMutexReadPriority is important here, because we want to make
545   // sure we don't block nested singleton creation happening concurrently with
546   // destroyInstances().
547   Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_;
548
549   Type type_;
550 };
551
552 // This is the wrapper class that most users actually interact with.
553 // It allows for simple access to registering and instantiating
554 // singletons.  Create instances of this class in the global scope of
555 // type Singleton<T> to register your singleton for later access via
556 // Singleton<T>::try_get().
557 template <
558     typename T,
559     typename Tag = detail::DefaultTag,
560     typename VaultTag = detail::DefaultTag /* for testing */>
561 class Singleton {
562  public:
563   typedef std::function<T*(void)> CreateFunc;
564   typedef std::function<void(T*)> TeardownFunc;
565
566   // Generally your program life cycle should be fine with calling
567   // get() repeatedly rather than saving the reference, and then not
568   // call get() during process shutdown.
569   FOLLY_DEPRECATED("Replaced by try_get")
570   static T* get() { return getEntry().get(); }
571
572   // If, however, you do need to hold a reference to the specific
573   // singleton, you can try to do so with a weak_ptr.  Avoid this when
574   // possible but the inability to lock the weak pointer can be a
575   // signal that the vault has been destroyed.
576   FOLLY_DEPRECATED("Replaced by try_get")
577   static std::weak_ptr<T> get_weak() { return getEntry().get_weak(); }
578
579   // Preferred alternative to get_weak, it returns shared_ptr that can be
580   // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
581   // Avoid holding these shared_ptrs beyond the scope of a function;
582   // don't put them in member variables, always use try_get() instead
583   //
584   // try_get() can return nullptr if the singleton was destroyed, caller is
585   // responsible for handling nullptr return
586   static std::shared_ptr<T> try_get() {
587     return getEntry().try_get();
588   }
589
590   static folly::ReadMostlySharedPtr<T> try_get_fast() {
591     return getEntry().try_get_fast();
592   }
593
594   explicit Singleton(std::nullptr_t /* _ */ = nullptr,
595                      typename Singleton::TeardownFunc t = nullptr)
596       : Singleton([]() { return new T; }, std::move(t)) {}
597
598   explicit Singleton(typename Singleton::CreateFunc c,
599                      typename Singleton::TeardownFunc t = nullptr) {
600     if (c == nullptr) {
601       detail::singletonThrowNullCreator(typeid(T));
602     }
603
604     auto vault = SingletonVault::singleton<VaultTag>();
605     getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
606     vault->registerSingleton(&getEntry());
607   }
608
609   /**
610    * Should be instantiated as soon as "doEagerInit[Via]" is called.
611    * Singletons are usually lazy-loaded (built on-demand) but for those which
612    * are known to be needed, to avoid the potential lag for objects that take
613    * long to construct during runtime, there is an option to make sure these
614    * are built up-front.
615    *
616    * Use like:
617    *   Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
618    *
619    * Or alternately, define the singleton as usual, and say
620    *   gFooInstance.shouldEagerInit();
621    *
622    * at some point prior to calling registrationComplete().
623    * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
624    */
625   Singleton& shouldEagerInit() {
626     auto vault = SingletonVault::singleton<VaultTag>();
627     vault->addEagerInitSingleton(&getEntry());
628     return *this;
629   }
630
631   /**
632   * Construct and inject a mock singleton which should be used only from tests.
633   * Unlike regular singletons which are initialized once per process lifetime,
634   * mock singletons live for the duration of a test. This means that one process
635   * running multiple tests can initialize and register the same singleton
636   * multiple times. This functionality should be used only from tests
637   * since it relaxes validation and performance in order to be able to perform
638   * the injection. The returned mock singleton is functionality identical to
639   * regular singletons.
640   */
641   static void make_mock(std::nullptr_t /* c */ = nullptr,
642                         typename Singleton<T>::TeardownFunc t = nullptr) {
643     make_mock([]() { return new T; }, t);
644   }
645
646   static void make_mock(CreateFunc c,
647                         typename Singleton<T>::TeardownFunc t = nullptr) {
648     if (c == nullptr) {
649       detail::singletonThrowNullCreator(typeid(T));
650     }
651
652     auto& entry = getEntry();
653
654     entry.registerSingletonMock(c, getTeardownFunc(t));
655   }
656
657  private:
658   inline static detail::SingletonHolder<T>& getEntry() {
659     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
660   }
661
662   // Construct TeardownFunc.
663   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
664       TeardownFunc t)  {
665     if (t == nullptr) {
666       return  [](T* v) { delete v; };
667     } else {
668       return t;
669     }
670   }
671 };
672
673 template <typename T, typename Tag = detail::DefaultTag>
674 class LeakySingleton {
675  public:
676   using CreateFunc = std::function<T*()>;
677
678   LeakySingleton() : LeakySingleton([] { return new T(); }) {}
679
680   explicit LeakySingleton(CreateFunc createFunc) {
681     auto& entry = entryInstance();
682     if (entry.state != State::NotRegistered) {
683       detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_);
684     }
685     entry.createFunc = createFunc;
686     entry.state = State::Dead;
687   }
688
689   static T& get() { return instance(); }
690
691   static void make_mock(std::nullptr_t /* c */ = nullptr) {
692     make_mock([]() { return new T; });
693   }
694
695   static void make_mock(CreateFunc createFunc) {
696     if (createFunc == nullptr) {
697       detail::singletonThrowNullCreator(typeid(T));
698     }
699
700     auto& entry = entryInstance();
701     entry.createFunc = createFunc;
702     entry.state = State::Dead;
703   }
704
705  private:
706   enum class State { NotRegistered, Dead, Living };
707
708   struct Entry {
709     Entry() {}
710     Entry(const Entry&) = delete;
711     Entry& operator=(const Entry&) = delete;
712
713     std::atomic<State> state{State::NotRegistered};
714     T* ptr{nullptr};
715     CreateFunc createFunc;
716     std::mutex mutex;
717     detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
718   };
719
720   static Entry& entryInstance() {
721     /* library-local */ static auto entry = detail::createGlobal<Entry, Tag>();
722     return *entry;
723   }
724
725   static T& instance() {
726     auto& entry = entryInstance();
727     if (UNLIKELY(entry.state != State::Living)) {
728       createInstance();
729     }
730
731     return *entry.ptr;
732   }
733
734   static void createInstance() {
735     auto& entry = entryInstance();
736
737     std::lock_guard<std::mutex> lg(entry.mutex);
738     if (entry.state == State::Living) {
739       return;
740     }
741
742     if (entry.state == State::NotRegistered) {
743       detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_);
744     }
745
746     entry.ptr = entry.createFunc();
747     entry.state = State::Living;
748   }
749 };
750 } // namespace folly
751
752 #include <folly/Singleton-inl.h>