2 * Copyright 2014-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 // SingletonVault - a library to manage the creation and destruction
17 // of interdependent singletons.
19 // Recommended usage of this class: suppose you have a class
20 // called MyExpensiveService, and you only want to construct one (ie,
21 // it's a singleton), but you only want to construct it if it is used.
24 // class MyExpensiveService {
25 // // Caution - may return a null ptr during startup and shutdown.
26 // static std::shared_ptr<MyExpensiveService> getInstance();
31 // namespace { struct PrivateTag {}; }
32 // static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton;
33 // std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() {
34 // return the_singleton.try_get();
37 // Code in other modules can access it via:
39 // auto instance = MyExpensiveService::getInstance();
41 // Advanced usage and notes:
43 // You can also access a singleton instance with
44 // `Singleton<ObjectType, TagType>::try_get()`. We recommend
45 // that you prefer the form `the_singleton.try_get()` because it ensures that
46 // `the_singleton` is used and cannot be garbage-collected during linking: this
47 // is necessary because the constructor of `the_singleton` is what registers it
48 // to the SingletonVault.
50 // The singleton will be created on demand. If the constructor for
51 // MyExpensiveService actually makes use of *another* Singleton, then
52 // the right thing will happen -- that other singleton will complete
53 // construction before get() returns. However, in the event of a
54 // circular dependency, a runtime error will occur.
56 // You can have multiple singletons of the same underlying type, but
57 // each must be given a unique tag. If no tag is specified a default tag is
58 // used. We recommend that you use a tag from an anonymous namespace private to
59 // your implementation file, as this ensures that the singleton is only
60 // available via your interface and not also through Singleton<T>::try_get()
65 // folly::Singleton<MyExpensiveService> s_default;
66 // folly::Singleton<MyExpensiveService, Tag1> s1;
67 // folly::Singleton<MyExpensiveService, Tag2> s2;
70 // MyExpensiveService* svc_default = s_default.get();
71 // MyExpensiveService* svc1 = s1.get();
72 // MyExpensiveService* svc2 = s2.get();
74 // By default, the singleton instance is constructed via new and
75 // deleted via delete, but this is configurable:
77 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
80 // Where create and destroy are functions, Singleton<T>::CreateFunc
81 // Singleton<T>::TeardownFunc.
83 // For example, if you need to pass arguments to your class's constructor:
86 // X(int a1, std::string a2);
89 // Make your singleton like this:
90 // folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); });
92 // The above examples detail a situation where an expensive singleton is loaded
93 // on-demand (thus only if needed). However if there is an expensive singleton
94 // that will likely be needed, and initialization takes a potentially long time,
95 // e.g. while initializing, parsing some files, talking to remote services,
96 // making uses of other singletons, and so on, the initialization of those can
97 // be scheduled up front, or "eagerly".
99 // In that case the singleton can be declared this way:
102 // auto the_singleton =
103 // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
104 // .shouldEagerInit();
107 // This way the singleton's instance is built at program initialization,
108 // if the program opted-in to that feature by calling "doEagerInit" or
109 // "doEagerInitVia" during its startup.
111 // What if you need to destroy all of your singletons? Say, some of
112 // your singletons manage threads, but you need to fork? Or your unit
113 // test wants to clean up all global state? Then you can call
114 // SingletonVault::singleton()->destroyInstances(), which invokes the
115 // TeardownFunc for each singleton, in the reverse order they were
116 // created. It is your responsibility to ensure your singletons can
117 // handle cases where the singletons they depend on go away, however.
118 // Singletons won't be recreated after destroyInstances call. If you
119 // want to re-enable singleton creation (say after fork was called) you
120 // should call reenableInstances.
124 #include <folly/Exception.h>
125 #include <folly/Executor.h>
126 #include <folly/Memory.h>
127 #include <folly/Synchronized.h>
128 #include <folly/detail/StaticSingletonManager.h>
129 #include <folly/experimental/ReadMostlySharedPtr.h>
130 #include <folly/hash/Hash.h>
131 #include <folly/synchronization/Baton.h>
132 #include <folly/synchronization/RWSpinLock.h>
136 #include <condition_variable>
137 #include <functional>
144 #include <unordered_map>
145 #include <unordered_set>
148 #include <glog/logging.h>
150 // use this guard to handleSingleton breaking change in 3rd party code
151 #ifndef FOLLY_SINGLETON_TRY_GET
152 #define FOLLY_SINGLETON_TRY_GET
157 // For actual usage, please see the Singleton<T> class at the bottom
158 // of this file; that is what you will actually interact with.
160 // SingletonVault is the class that manages singleton instances. It
161 // is unaware of the underlying types of singletons, and simply
162 // manages lifecycles and invokes CreateFunc and TeardownFunc when
163 // appropriate. In general, you won't need to interact with the
164 // SingletonVault itself.
166 // A vault goes through a few stages of life:
168 // 1. Registration phase; singletons can be registered:
169 // a) Strict: no singleton can be created in this stage.
170 // b) Relaxed: singleton can be created (the default vault is Relaxed).
171 // 2. registrationComplete() has been called; singletons can no
172 // longer be registered, but they can be created.
173 // 3. A vault can return to stage 1 when destroyInstances is called.
175 // In general, you don't need to worry about any of the above; just
176 // ensure registrationComplete() is called near the top of your main()
177 // function, otherwise no singletons can be instantiated.
179 class SingletonVault;
183 struct DefaultTag {};
185 // A TypeDescriptor is the unique handle for a given singleton. It is
186 // a combinaiton of the type and of the optional name, and is used as
187 // a key in unordered_maps.
188 class TypeDescriptor {
190 TypeDescriptor(const std::type_info& ti,
191 const std::type_info& tag_ti)
192 : ti_(ti), tag_ti_(tag_ti) {
195 TypeDescriptor(const TypeDescriptor& other)
196 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
199 TypeDescriptor& operator=(const TypeDescriptor& other) {
200 if (this != &other) {
202 tag_ti_ = other.tag_ti_;
208 std::string name() const;
210 friend class TypeDescriptorHasher;
212 bool operator==(const TypeDescriptor& other) const {
213 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
218 std::type_index tag_ti_;
221 class TypeDescriptorHasher {
223 size_t operator()(const TypeDescriptor& ti) const {
224 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
228 [[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
229 const TypeDescriptor& type);
231 [[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
232 const TypeDescriptor& type);
234 [[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
235 const TypeDescriptor& type);
237 void singletonWarnDestroyInstanceLeak(
238 const TypeDescriptor& type,
241 [[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
242 const TypeDescriptor& type);
244 [[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
245 const TypeDescriptor& type);
247 [[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
248 const TypeDescriptor& type);
250 void singletonPrintDestructionStackTrace(const TypeDescriptor& type);
252 [[noreturn]] void singletonThrowNullCreator(const std::type_info& type);
254 [[noreturn]] void singletonThrowGetInvokedAfterDestruction(
255 const TypeDescriptor& type);
257 struct SingletonVaultState {
258 // The two stages of life for a vault, as mentioned in the class comment.
264 Type state{Type::Running};
265 bool registrationComplete{false};
267 // Each singleton in the vault can be in two states: dead
268 // (registered but never created), living (CreateFunc returned an instance).
272 const char* msg = "Unexpected singleton state change") const {
273 if (expected != state) {
274 throwUnexpectedState(msg);
278 [[noreturn]] static void throwUnexpectedState(const char* msg);
281 // This interface is used by SingletonVault to interact with SingletonHolders.
282 // Having a non-template interface allows SingletonVault to keep a list of all
284 class SingletonHolderBase {
286 explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {}
287 virtual ~SingletonHolderBase() = default;
289 TypeDescriptor type() const {
292 virtual bool hasLiveInstance() = 0;
293 virtual void createInstance() = 0;
294 virtual bool creationStarted() = 0;
295 virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0;
296 virtual void destroyInstance() = 0;
299 TypeDescriptor type_;
302 // An actual instance of a singleton, tracking the instance itself,
303 // its state as described above, and the create and teardown
305 template <typename T>
306 struct SingletonHolder : public SingletonHolderBase {
308 typedef std::function<void(T*)> TeardownFunc;
309 typedef std::function<T*(void)> CreateFunc;
311 template <typename Tag, typename VaultTag>
312 inline static SingletonHolder<T>& singleton();
315 inline std::weak_ptr<T> get_weak();
316 inline std::shared_ptr<T> try_get();
317 inline folly::ReadMostlySharedPtr<T> try_get_fast();
319 void registerSingleton(CreateFunc c, TeardownFunc t);
320 void registerSingletonMock(CreateFunc c, TeardownFunc t);
321 bool hasLiveInstance() override;
322 void createInstance() override;
323 bool creationStarted() override;
324 void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override;
325 void destroyInstance() override;
328 SingletonHolder(TypeDescriptor type, SingletonVault& vault);
330 enum class SingletonHolderState {
336 SingletonVault& vault_;
338 // mutex protects the entire entry during construction/destruction
341 // State of the singleton entry. If state is Living, instance_ptr and
342 // instance_weak can be safely accessed w/o synchronization.
343 std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
345 // the thread creating the singleton (only valid while creating an object)
346 std::atomic<std::thread::id> creating_thread_;
348 // The singleton itself and related functions.
350 // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
351 // from Dead to Living. Reset when state is changed from Living to Dead.
352 folly::ReadMostlyMainPtr<T> instance_;
353 // used to release all ReadMostlyMainPtrs at once
354 folly::ReadMostlySharedPtr<T> instance_copy_;
355 // weak_ptr to the singleton instance, set when state is changed from Dead
356 // to Living. We never write to this object after initialization, so it is
357 // safe to read it from different threads w/o synchronization if we know
358 // that state is set to Living
359 std::weak_ptr<T> instance_weak_;
360 // Fast equivalent of instance_weak_
361 folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
362 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
363 std::shared_ptr<folly::Baton<>> destroy_baton_;
364 T* instance_ptr_ = nullptr;
365 CreateFunc create_ = nullptr;
366 TeardownFunc teardown_ = nullptr;
368 std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
370 SingletonHolder(const SingletonHolder&) = delete;
371 SingletonHolder& operator=(const SingletonHolder&) = delete;
372 SingletonHolder& operator=(SingletonHolder&&) = delete;
373 SingletonHolder(SingletonHolder&&) = delete;
376 } // namespace detail
378 class SingletonVault {
381 Strict, // Singletons can't be created before registrationComplete()
382 Relaxed, // Singletons can be created before registrationComplete()
386 * Clears all singletons in the given vault at ctor and dtor times.
387 * Useful for unit-tests that need to clear the world.
389 * This need can arise when a unit-test needs to swap out an object used by a
390 * singleton for a test-double, but the singleton needing its dependency to be
391 * swapped has a type or a tag local to some other translation unit and
392 * unavailable in the current translation unit.
394 * Other, better approaches to this need are "plz 2 refactor" ....
396 struct ScopedExpunger {
397 SingletonVault* vault;
398 explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
399 ~ScopedExpunger() { expunge(); }
401 vault->destroyInstances();
402 vault->reenableInstances();
406 static Type defaultVaultType();
408 explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {}
410 // Destructor is only called by unit tests to check destroyInstances.
413 typedef std::function<void(void*)> TeardownFunc;
414 typedef std::function<void*(void)> CreateFunc;
416 // Ensure that Singleton has not been registered previously and that
417 // registration is not complete. If validations succeeds,
418 // register a singleton of a given type with the create and teardown
420 void registerSingleton(detail::SingletonHolderBase* entry);
423 * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
424 * is built when `doEagerInit[Via]` is called; see those methods
427 void addEagerInitSingleton(detail::SingletonHolderBase* entry);
429 // Mark registration is complete; no more singletons can be
430 // registered at this point.
431 void registrationComplete();
434 * Initialize all singletons which were marked as eager-initialized
435 * (using `shouldEagerInit()`). No return value. Propagates exceptions
436 * from constructors / create functions, as is the usual case when calling
437 * for example `Singleton<Foo>::get_weak()`.
442 * Schedule eager singletons' initializations through the given executor.
443 * If baton ptr is not null, its `post` method is called after all
444 * early initialization has completed.
446 * If exceptions are thrown during initialization, this method will still
447 * `post` the baton to indicate completion. The exception will not propagate
448 * and future attempts to `try_get` or `get_weak` the failed singleton will
449 * retry initialization.
453 * folly::IOThreadPoolExecutor executor(max_concurrency_level);
454 * folly::Baton<> done;
455 * doEagerInitVia(executor, &done);
456 * done.wait(); // or 'try_wait_for', etc.
459 void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
461 // Destroy all singletons; when complete, the vault can't create
462 // singletons once again until reenableInstances() is called.
463 void destroyInstances();
465 // Enable re-creating singletons after destroyInstances() was called.
466 void reenableInstances();
468 // For testing; how many registered and living singletons we have.
469 size_t registeredSingletonCount() const {
470 return singletons_.rlock()->size();
474 * Flips to true if eager initialization was used, and has completed.
475 * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
477 bool eagerInitComplete() const;
479 size_t livingSingletonCount() const {
480 auto singletons = singletons_.rlock();
483 for (const auto& p : *singletons) {
484 if (p.second->hasLiveInstance()) {
492 // A well-known vault; you can actually have others, but this is the
494 static SingletonVault* singleton() {
495 return singleton<>();
498 // Gets singleton vault for any Tag. Non-default tag should be used in unit
500 template <typename VaultTag = detail::DefaultTag>
501 static SingletonVault* singleton() {
502 /* library-local */ static auto vault =
503 detail::createGlobal<SingletonVault, VaultTag>();
507 typedef std::string(*StackTraceGetterPtr)();
509 static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
510 /* library-local */ static auto stackTraceGetterPtr = detail::
511 createGlobal<std::atomic<StackTraceGetterPtr>, SingletonVault>();
512 return *stackTraceGetterPtr;
515 void setType(Type type) {
520 template <typename T>
521 friend struct detail::SingletonHolder;
523 // This method only matters if registrationComplete() is never called.
524 // Otherwise destroyInstances is scheduled to be executed atexit.
526 // Initializes static object, which calls destroyInstances on destruction.
527 // Used to have better deletion ordering with singleton not managed by
528 // folly::Singleton. The desruction will happen in the following order:
529 // 1. Singletons, not managed by folly::Singleton, which were created after
530 // any of the singletons managed by folly::Singleton was requested.
531 // 2. All singletons managed by folly::Singleton
532 // 3. Singletons, not managed by folly::Singleton, which were created before
533 // any of the singletons managed by folly::Singleton was requested.
534 static void scheduleDestroyInstances();
536 typedef std::unordered_map<detail::TypeDescriptor,
537 detail::SingletonHolderBase*,
538 detail::TypeDescriptorHasher> SingletonMap;
539 Synchronized<SingletonMap> singletons_;
540 Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
541 eagerInitSingletons_;
542 Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
544 // Using SharedMutexReadPriority is important here, because we want to make
545 // sure we don't block nested singleton creation happening concurrently with
546 // destroyInstances().
547 Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_;
552 // This is the wrapper class that most users actually interact with.
553 // It allows for simple access to registering and instantiating
554 // singletons. Create instances of this class in the global scope of
555 // type Singleton<T> to register your singleton for later access via
556 // Singleton<T>::try_get().
559 typename Tag = detail::DefaultTag,
560 typename VaultTag = detail::DefaultTag /* for testing */>
563 typedef std::function<T*(void)> CreateFunc;
564 typedef std::function<void(T*)> TeardownFunc;
566 // Generally your program life cycle should be fine with calling
567 // get() repeatedly rather than saving the reference, and then not
568 // call get() during process shutdown.
569 FOLLY_DEPRECATED("Replaced by try_get")
570 static T* get() { return getEntry().get(); }
572 // If, however, you do need to hold a reference to the specific
573 // singleton, you can try to do so with a weak_ptr. Avoid this when
574 // possible but the inability to lock the weak pointer can be a
575 // signal that the vault has been destroyed.
576 FOLLY_DEPRECATED("Replaced by try_get")
577 static std::weak_ptr<T> get_weak() { return getEntry().get_weak(); }
579 // Preferred alternative to get_weak, it returns shared_ptr that can be
580 // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
581 // Avoid holding these shared_ptrs beyond the scope of a function;
582 // don't put them in member variables, always use try_get() instead
584 // try_get() can return nullptr if the singleton was destroyed, caller is
585 // responsible for handling nullptr return
586 static std::shared_ptr<T> try_get() {
587 return getEntry().try_get();
590 static folly::ReadMostlySharedPtr<T> try_get_fast() {
591 return getEntry().try_get_fast();
594 explicit Singleton(std::nullptr_t /* _ */ = nullptr,
595 typename Singleton::TeardownFunc t = nullptr)
596 : Singleton([]() { return new T; }, std::move(t)) {}
598 explicit Singleton(typename Singleton::CreateFunc c,
599 typename Singleton::TeardownFunc t = nullptr) {
601 detail::singletonThrowNullCreator(typeid(T));
604 auto vault = SingletonVault::singleton<VaultTag>();
605 getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
606 vault->registerSingleton(&getEntry());
610 * Should be instantiated as soon as "doEagerInit[Via]" is called.
611 * Singletons are usually lazy-loaded (built on-demand) but for those which
612 * are known to be needed, to avoid the potential lag for objects that take
613 * long to construct during runtime, there is an option to make sure these
614 * are built up-front.
617 * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
619 * Or alternately, define the singleton as usual, and say
620 * gFooInstance.shouldEagerInit();
622 * at some point prior to calling registrationComplete().
623 * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
625 Singleton& shouldEagerInit() {
626 auto vault = SingletonVault::singleton<VaultTag>();
627 vault->addEagerInitSingleton(&getEntry());
632 * Construct and inject a mock singleton which should be used only from tests.
633 * Unlike regular singletons which are initialized once per process lifetime,
634 * mock singletons live for the duration of a test. This means that one process
635 * running multiple tests can initialize and register the same singleton
636 * multiple times. This functionality should be used only from tests
637 * since it relaxes validation and performance in order to be able to perform
638 * the injection. The returned mock singleton is functionality identical to
639 * regular singletons.
641 static void make_mock(std::nullptr_t /* c */ = nullptr,
642 typename Singleton<T>::TeardownFunc t = nullptr) {
643 make_mock([]() { return new T; }, t);
646 static void make_mock(CreateFunc c,
647 typename Singleton<T>::TeardownFunc t = nullptr) {
649 detail::singletonThrowNullCreator(typeid(T));
652 auto& entry = getEntry();
654 entry.registerSingletonMock(c, getTeardownFunc(t));
658 inline static detail::SingletonHolder<T>& getEntry() {
659 return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
662 // Construct TeardownFunc.
663 static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
666 return [](T* v) { delete v; };
673 template <typename T, typename Tag = detail::DefaultTag>
674 class LeakySingleton {
676 using CreateFunc = std::function<T*()>;
678 LeakySingleton() : LeakySingleton([] { return new T(); }) {}
680 explicit LeakySingleton(CreateFunc createFunc) {
681 auto& entry = entryInstance();
682 if (entry.state != State::NotRegistered) {
683 detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_);
685 entry.createFunc = createFunc;
686 entry.state = State::Dead;
689 static T& get() { return instance(); }
691 static void make_mock(std::nullptr_t /* c */ = nullptr) {
692 make_mock([]() { return new T; });
695 static void make_mock(CreateFunc createFunc) {
696 if (createFunc == nullptr) {
697 detail::singletonThrowNullCreator(typeid(T));
700 auto& entry = entryInstance();
701 entry.createFunc = createFunc;
702 entry.state = State::Dead;
706 enum class State { NotRegistered, Dead, Living };
710 Entry(const Entry&) = delete;
711 Entry& operator=(const Entry&) = delete;
713 std::atomic<State> state{State::NotRegistered};
715 CreateFunc createFunc;
717 detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
720 static Entry& entryInstance() {
721 /* library-local */ static auto entry = detail::createGlobal<Entry, Tag>();
725 static T& instance() {
726 auto& entry = entryInstance();
727 if (UNLIKELY(entry.state != State::Living)) {
734 static void createInstance() {
735 auto& entry = entryInstance();
737 std::lock_guard<std::mutex> lg(entry.mutex);
738 if (entry.state == State::Living) {
742 if (entry.state == State::NotRegistered) {
743 detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_);
746 entry.ptr = entry.createFunc();
747 entry.state = State::Living;
752 #include <folly/Singleton-inl.h>