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