2 * Copyright 2017 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.
17 // SingletonVault - a library to manage the creation and destruction
18 // of interdependent singletons.
20 // Recommended usage of this class: suppose you have a class
21 // called MyExpensiveService, and you only want to construct one (ie,
22 // it's a singleton), but you only want to construct it if it is used.
25 // class MyExpensiveService {
26 // // Caution - may return a null ptr during startup and shutdown.
27 // static std::shared_ptr<MyExpensiveService> getInstance();
32 // namespace { struct PrivateTag {}; }
33 // static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton;
34 // std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() {
35 // return the_singleton.try_get();
38 // Code in other modules can access it via:
40 // auto instance = MyExpensiveService::getInstance();
42 // Advanced usage and notes:
44 // You can also access a singleton instance with
45 // `Singleton<ObjectType, TagType>::try_get()`. We recommend
46 // that you prefer the form `the_singleton.try_get()` because it ensures that
47 // `the_singleton` is used and cannot be garbage-collected during linking: this
48 // is necessary because the constructor of `the_singleton` is what registers it
49 // to the SingletonVault.
51 // The singleton will be created on demand. If the constructor for
52 // MyExpensiveService actually makes use of *another* Singleton, then
53 // the right thing will happen -- that other singleton will complete
54 // construction before get() returns. However, in the event of a
55 // circular dependency, a runtime error will occur.
57 // You can have multiple singletons of the same underlying type, but
58 // each must be given a unique tag. If no tag is specified a default tag is
59 // used. We recommend that you use a tag from an anonymous namespace private to
60 // your implementation file, as this ensures that the singleton is only
61 // available via your interface and not also through Singleton<T>::try_get()
66 // folly::Singleton<MyExpensiveService> s_default;
67 // folly::Singleton<MyExpensiveService, Tag1> s1;
68 // folly::Singleton<MyExpensiveService, Tag2> s2;
71 // MyExpensiveService* svc_default = s_default.get();
72 // MyExpensiveService* svc1 = s1.get();
73 // MyExpensiveService* svc2 = s2.get();
75 // By default, the singleton instance is constructed via new and
76 // deleted via delete, but this is configurable:
78 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
81 // Where create and destroy are functions, Singleton<T>::CreateFunc
82 // Singleton<T>::TeardownFunc.
84 // For example, if you need to pass arguments to your class's constructor:
87 // X(int a1, std::string a2);
90 // Make your singleton like this:
91 // folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); });
93 // The above examples detail a situation where an expensive singleton is loaded
94 // on-demand (thus only if needed). However if there is an expensive singleton
95 // that will likely be needed, and initialization takes a potentially long time,
96 // e.g. while initializing, parsing some files, talking to remote services,
97 // making uses of other singletons, and so on, the initialization of those can
98 // be scheduled up front, or "eagerly".
100 // In that case the singleton can be declared this way:
103 // auto the_singleton =
104 // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
105 // .shouldEagerInit();
108 // This way the singleton's instance is built at program initialization,
109 // if the program opted-in to that feature by calling "doEagerInit" or
110 // "doEagerInitVia" during its startup.
112 // What if you need to destroy all of your singletons? Say, some of
113 // your singletons manage threads, but you need to fork? Or your unit
114 // test wants to clean up all global state? Then you can call
115 // SingletonVault::singleton()->destroyInstances(), which invokes the
116 // TeardownFunc for each singleton, in the reverse order they were
117 // created. It is your responsibility to ensure your singletons can
118 // handle cases where the singletons they depend on go away, however.
119 // Singletons won't be recreated after destroyInstances call. If you
120 // want to re-enable singleton creation (say after fork was called) you
121 // should call reenableInstances.
125 #include <folly/Exception.h>
126 #include <folly/Executor.h>
127 #include <folly/Memory.h>
128 #include <folly/RWSpinLock.h>
129 #include <folly/Synchronized.h>
130 #include <folly/detail/StaticSingletonManager.h>
131 #include <folly/experimental/ReadMostlySharedPtr.h>
132 #include <folly/hash/Hash.h>
133 #include <folly/synchronization/Baton.h>
137 #include <condition_variable>
138 #include <functional>
145 #include <unordered_map>
146 #include <unordered_set>
149 #include <glog/logging.h>
151 // use this guard to handleSingleton breaking change in 3rd party code
152 #ifndef FOLLY_SINGLETON_TRY_GET
153 #define FOLLY_SINGLETON_TRY_GET
158 // For actual usage, please see the Singleton<T> class at the bottom
159 // of this file; that is what you will actually interact with.
161 // SingletonVault is the class that manages singleton instances. It
162 // is unaware of the underlying types of singletons, and simply
163 // manages lifecycles and invokes CreateFunc and TeardownFunc when
164 // appropriate. In general, you won't need to interact with the
165 // SingletonVault itself.
167 // A vault goes through a few stages of life:
169 // 1. Registration phase; singletons can be registered:
170 // a) Strict: no singleton can be created in this stage.
171 // b) Relaxed: singleton can be created (the default vault is Relaxed).
172 // 2. registrationComplete() has been called; singletons can no
173 // longer be registered, but they can be created.
174 // 3. A vault can return to stage 1 when destroyInstances is called.
176 // In general, you don't need to worry about any of the above; just
177 // ensure registrationComplete() is called near the top of your main()
178 // function, otherwise no singletons can be instantiated.
180 class SingletonVault;
184 struct DefaultTag {};
186 // A TypeDescriptor is the unique handle for a given singleton. It is
187 // a combinaiton of the type and of the optional name, and is used as
188 // a key in unordered_maps.
189 class TypeDescriptor {
191 TypeDescriptor(const std::type_info& ti,
192 const std::type_info& tag_ti)
193 : ti_(ti), tag_ti_(tag_ti) {
196 TypeDescriptor(const TypeDescriptor& other)
197 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
200 TypeDescriptor& operator=(const TypeDescriptor& other) {
201 if (this != &other) {
203 tag_ti_ = other.tag_ti_;
209 std::string name() const;
211 friend class TypeDescriptorHasher;
213 bool operator==(const TypeDescriptor& other) const {
214 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
219 std::type_index tag_ti_;
222 class TypeDescriptorHasher {
224 size_t operator()(const TypeDescriptor& ti) const {
225 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
229 [[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
230 const TypeDescriptor& type);
232 [[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
233 const TypeDescriptor& type);
235 [[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
236 const TypeDescriptor& type);
238 void singletonWarnDestroyInstanceLeak(
239 const TypeDescriptor& type,
242 [[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
243 const TypeDescriptor& type);
245 [[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
246 const TypeDescriptor& type);
248 [[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
249 const TypeDescriptor& type);
251 void singletonPrintDestructionStackTrace(const TypeDescriptor& type);
253 [[noreturn]] void singletonThrowNullCreator(const std::type_info& type);
255 [[noreturn]] void singletonThrowGetInvokedAfterDestruction(
256 const TypeDescriptor& type);
258 struct SingletonVaultState {
259 // The two stages of life for a vault, as mentioned in the class comment.
265 Type state{Type::Running};
266 bool registrationComplete{false};
268 // Each singleton in the vault can be in two states: dead
269 // (registered but never created), living (CreateFunc returned an instance).
273 const char* msg = "Unexpected singleton state change") const {
274 if (expected != state) {
275 throwUnexpectedState(msg);
279 [[noreturn]] static void throwUnexpectedState(const char* msg);
282 // This interface is used by SingletonVault to interact with SingletonHolders.
283 // Having a non-template interface allows SingletonVault to keep a list of all
285 class SingletonHolderBase {
287 explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {}
288 virtual ~SingletonHolderBase() = default;
290 TypeDescriptor type() const {
293 virtual bool hasLiveInstance() = 0;
294 virtual void createInstance() = 0;
295 virtual bool creationStarted() = 0;
296 virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0;
297 virtual void destroyInstance() = 0;
300 TypeDescriptor type_;
303 // An actual instance of a singleton, tracking the instance itself,
304 // its state as described above, and the create and teardown
306 template <typename T>
307 struct SingletonHolder : public SingletonHolderBase {
309 typedef std::function<void(T*)> TeardownFunc;
310 typedef std::function<T*(void)> CreateFunc;
312 template <typename Tag, typename VaultTag>
313 inline static SingletonHolder<T>& singleton();
316 inline std::weak_ptr<T> get_weak();
317 inline std::shared_ptr<T> try_get();
318 inline folly::ReadMostlySharedPtr<T> try_get_fast();
320 void registerSingleton(CreateFunc c, TeardownFunc t);
321 void registerSingletonMock(CreateFunc c, TeardownFunc t);
322 bool hasLiveInstance() override;
323 void createInstance() override;
324 bool creationStarted() override;
325 void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override;
326 void destroyInstance() override;
329 SingletonHolder(TypeDescriptor type, SingletonVault& vault);
331 enum class SingletonHolderState {
337 SingletonVault& vault_;
339 // mutex protects the entire entry during construction/destruction
342 // State of the singleton entry. If state is Living, instance_ptr and
343 // instance_weak can be safely accessed w/o synchronization.
344 std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
346 // the thread creating the singleton (only valid while creating an object)
347 std::atomic<std::thread::id> creating_thread_;
349 // The singleton itself and related functions.
351 // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
352 // from Dead to Living. Reset when state is changed from Living to Dead.
353 folly::ReadMostlyMainPtr<T> instance_;
354 // used to release all ReadMostlyMainPtrs at once
355 folly::ReadMostlySharedPtr<T> instance_copy_;
356 // weak_ptr to the singleton instance, set when state is changed from Dead
357 // to Living. We never write to this object after initialization, so it is
358 // safe to read it from different threads w/o synchronization if we know
359 // that state is set to Living
360 std::weak_ptr<T> instance_weak_;
361 // Fast equivalent of instance_weak_
362 folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
363 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
364 std::shared_ptr<folly::Baton<>> destroy_baton_;
365 T* instance_ptr_ = nullptr;
366 CreateFunc create_ = nullptr;
367 TeardownFunc teardown_ = nullptr;
369 std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
371 SingletonHolder(const SingletonHolder&) = delete;
372 SingletonHolder& operator=(const SingletonHolder&) = delete;
373 SingletonHolder& operator=(SingletonHolder&&) = delete;
374 SingletonHolder(SingletonHolder&&) = delete;
377 } // namespace detail
379 class SingletonVault {
382 Strict, // Singletons can't be created before registrationComplete()
383 Relaxed, // Singletons can be created before registrationComplete()
387 * Clears all singletons in the given vault at ctor and dtor times.
388 * Useful for unit-tests that need to clear the world.
390 * This need can arise when a unit-test needs to swap out an object used by a
391 * singleton for a test-double, but the singleton needing its dependency to be
392 * swapped has a type or a tag local to some other translation unit and
393 * unavailable in the current translation unit.
395 * Other, better approaches to this need are "plz 2 refactor" ....
397 struct ScopedExpunger {
398 SingletonVault* vault;
399 explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
400 ~ScopedExpunger() { expunge(); }
402 vault->destroyInstances();
403 vault->reenableInstances();
407 static Type defaultVaultType();
409 explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {}
411 // Destructor is only called by unit tests to check destroyInstances.
414 typedef std::function<void(void*)> TeardownFunc;
415 typedef std::function<void*(void)> CreateFunc;
417 // Ensure that Singleton has not been registered previously and that
418 // registration is not complete. If validations succeeds,
419 // register a singleton of a given type with the create and teardown
421 void registerSingleton(detail::SingletonHolderBase* entry);
424 * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
425 * is built when `doEagerInit[Via]` is called; see those methods
428 void addEagerInitSingleton(detail::SingletonHolderBase* entry);
430 // Mark registration is complete; no more singletons can be
431 // registered at this point.
432 void registrationComplete();
435 * Initialize all singletons which were marked as eager-initialized
436 * (using `shouldEagerInit()`). No return value. Propagates exceptions
437 * from constructors / create functions, as is the usual case when calling
438 * for example `Singleton<Foo>::get_weak()`.
443 * Schedule eager singletons' initializations through the given executor.
444 * If baton ptr is not null, its `post` method is called after all
445 * early initialization has completed.
447 * If exceptions are thrown during initialization, this method will still
448 * `post` the baton to indicate completion. The exception will not propagate
449 * and future attempts to `try_get` or `get_weak` the failed singleton will
450 * retry initialization.
454 * folly::IOThreadPoolExecutor executor(max_concurrency_level);
455 * folly::Baton<> done;
456 * doEagerInitVia(executor, &done);
457 * done.wait(); // or 'try_wait_for', etc.
460 void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
462 // Destroy all singletons; when complete, the vault can't create
463 // singletons once again until reenableInstances() is called.
464 void destroyInstances();
466 // Enable re-creating singletons after destroyInstances() was called.
467 void reenableInstances();
469 // For testing; how many registered and living singletons we have.
470 size_t registeredSingletonCount() const {
471 return singletons_.rlock()->size();
475 * Flips to true if eager initialization was used, and has completed.
476 * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
478 bool eagerInitComplete() const;
480 size_t livingSingletonCount() const {
481 auto singletons = singletons_.rlock();
484 for (const auto& p : *singletons) {
485 if (p.second->hasLiveInstance()) {
493 // A well-known vault; you can actually have others, but this is the
495 static SingletonVault* singleton() {
496 return singleton<>();
499 // Gets singleton vault for any Tag. Non-default tag should be used in unit
501 template <typename VaultTag = detail::DefaultTag>
502 static SingletonVault* singleton() {
503 /* library-local */ static auto vault =
504 detail::createGlobal<SingletonVault, VaultTag>();
508 typedef std::string(*StackTraceGetterPtr)();
510 static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
511 /* library-local */ static auto stackTraceGetterPtr = detail::
512 createGlobal<std::atomic<StackTraceGetterPtr>, SingletonVault>();
513 return *stackTraceGetterPtr;
516 void setType(Type type) {
521 template <typename T>
522 friend struct detail::SingletonHolder;
524 // This method only matters if registrationComplete() is never called.
525 // Otherwise destroyInstances is scheduled to be executed atexit.
527 // Initializes static object, which calls destroyInstances on destruction.
528 // Used to have better deletion ordering with singleton not managed by
529 // folly::Singleton. The desruction will happen in the following order:
530 // 1. Singletons, not managed by folly::Singleton, which were created after
531 // any of the singletons managed by folly::Singleton was requested.
532 // 2. All singletons managed by folly::Singleton
533 // 3. Singletons, not managed by folly::Singleton, which were created before
534 // any of the singletons managed by folly::Singleton was requested.
535 static void scheduleDestroyInstances();
537 typedef std::unordered_map<detail::TypeDescriptor,
538 detail::SingletonHolderBase*,
539 detail::TypeDescriptorHasher> SingletonMap;
540 Synchronized<SingletonMap> singletons_;
541 Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
542 eagerInitSingletons_;
543 Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
545 // Using SharedMutexReadPriority is important here, because we want to make
546 // sure we don't block nested singleton creation happening concurrently with
547 // destroyInstances().
548 Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_;
553 // This is the wrapper class that most users actually interact with.
554 // It allows for simple access to registering and instantiating
555 // singletons. Create instances of this class in the global scope of
556 // type Singleton<T> to register your singleton for later access via
557 // Singleton<T>::try_get().
560 typename Tag = detail::DefaultTag,
561 typename VaultTag = detail::DefaultTag /* for testing */>
564 typedef std::function<T*(void)> CreateFunc;
565 typedef std::function<void(T*)> TeardownFunc;
567 // Generally your program life cycle should be fine with calling
568 // get() repeatedly rather than saving the reference, and then not
569 // call get() during process shutdown.
570 FOLLY_DEPRECATED("Replaced by try_get")
571 static T* get() { return getEntry().get(); }
573 // If, however, you do need to hold a reference to the specific
574 // singleton, you can try to do so with a weak_ptr. Avoid this when
575 // possible but the inability to lock the weak pointer can be a
576 // signal that the vault has been destroyed.
577 FOLLY_DEPRECATED("Replaced by try_get")
578 static std::weak_ptr<T> get_weak() { return getEntry().get_weak(); }
580 // Preferred alternative to get_weak, it returns shared_ptr that can be
581 // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
582 // Avoid holding these shared_ptrs beyond the scope of a function;
583 // don't put them in member variables, always use try_get() instead
585 // try_get() can return nullptr if the singleton was destroyed, caller is
586 // responsible for handling nullptr return
587 static std::shared_ptr<T> try_get() {
588 return getEntry().try_get();
591 static folly::ReadMostlySharedPtr<T> try_get_fast() {
592 return getEntry().try_get_fast();
595 explicit Singleton(std::nullptr_t /* _ */ = nullptr,
596 typename Singleton::TeardownFunc t = nullptr)
597 : Singleton([]() { return new T; }, std::move(t)) {}
599 explicit Singleton(typename Singleton::CreateFunc c,
600 typename Singleton::TeardownFunc t = nullptr) {
602 detail::singletonThrowNullCreator(typeid(T));
605 auto vault = SingletonVault::singleton<VaultTag>();
606 getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
607 vault->registerSingleton(&getEntry());
611 * Should be instantiated as soon as "doEagerInit[Via]" is called.
612 * Singletons are usually lazy-loaded (built on-demand) but for those which
613 * are known to be needed, to avoid the potential lag for objects that take
614 * long to construct during runtime, there is an option to make sure these
615 * are built up-front.
618 * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
620 * Or alternately, define the singleton as usual, and say
621 * gFooInstance.shouldEagerInit();
623 * at some point prior to calling registrationComplete().
624 * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
626 Singleton& shouldEagerInit() {
627 auto vault = SingletonVault::singleton<VaultTag>();
628 vault->addEagerInitSingleton(&getEntry());
633 * Construct and inject a mock singleton which should be used only from tests.
634 * Unlike regular singletons which are initialized once per process lifetime,
635 * mock singletons live for the duration of a test. This means that one process
636 * running multiple tests can initialize and register the same singleton
637 * multiple times. This functionality should be used only from tests
638 * since it relaxes validation and performance in order to be able to perform
639 * the injection. The returned mock singleton is functionality identical to
640 * regular singletons.
642 static void make_mock(std::nullptr_t /* c */ = nullptr,
643 typename Singleton<T>::TeardownFunc t = nullptr) {
644 make_mock([]() { return new T; }, t);
647 static void make_mock(CreateFunc c,
648 typename Singleton<T>::TeardownFunc t = nullptr) {
650 detail::singletonThrowNullCreator(typeid(T));
653 auto& entry = getEntry();
655 entry.registerSingletonMock(c, getTeardownFunc(t));
659 inline static detail::SingletonHolder<T>& getEntry() {
660 return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
663 // Construct TeardownFunc.
664 static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
667 return [](T* v) { delete v; };
674 template <typename T, typename Tag = detail::DefaultTag>
675 class LeakySingleton {
677 using CreateFunc = std::function<T*()>;
679 LeakySingleton() : LeakySingleton([] { return new T(); }) {}
681 explicit LeakySingleton(CreateFunc createFunc) {
682 auto& entry = entryInstance();
683 if (entry.state != State::NotRegistered) {
684 detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_);
686 entry.createFunc = createFunc;
687 entry.state = State::Dead;
690 static T& get() { return instance(); }
692 static void make_mock(std::nullptr_t /* c */ = nullptr) {
693 make_mock([]() { return new T; });
696 static void make_mock(CreateFunc createFunc) {
697 if (createFunc == nullptr) {
698 detail::singletonThrowNullCreator(typeid(T));
701 auto& entry = entryInstance();
702 entry.createFunc = createFunc;
703 entry.state = State::Dead;
707 enum class State { NotRegistered, Dead, Living };
711 Entry(const Entry&) = delete;
712 Entry& operator=(const Entry&) = delete;
714 std::atomic<State> state{State::NotRegistered};
716 CreateFunc createFunc;
718 detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
721 static Entry& entryInstance() {
722 /* library-local */ static auto entry = detail::createGlobal<Entry, Tag>();
726 static T& instance() {
727 auto& entry = entryInstance();
728 if (UNLIKELY(entry.state != State::Living)) {
735 static void createInstance() {
736 auto& entry = entryInstance();
738 std::lock_guard<std::mutex> lg(entry.mutex);
739 if (entry.state == State::Living) {
743 if (entry.state == State::NotRegistered) {
744 detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_);
747 entry.ptr = entry.createFunc();
748 entry.state = State::Living;
753 #include <folly/Singleton-inl.h>