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