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