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