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