2 * Copyright 2016 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 // 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.
25 // class MyExpensiveService { ... };
28 // namespace { folly::Singleton<MyExpensiveService> the_singleton; }
30 // Code can access it via:
32 // MyExpensiveService* instance = Singleton<MyExpensiveService>::get();
34 // std::weak_ptr<MyExpensiveService> instance =
35 // Singleton<MyExpensiveService>::get_weak();
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).
41 // Please note, however, that all non-weak_ptr interfaces are
42 // inherently subject to races with destruction. Use responsibly.
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.
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
56 // folly::Singleton<MyExpensiveService> s_default;
57 // folly::Singleton<MyExpensiveService, Tag1> s1;
58 // folly::Singleton<MyExpensiveService, Tag2> s2;
61 // MyExpensiveService* svc_default = s_default.get();
62 // MyExpensiveService* svc1 = s1.get();
63 // MyExpensiveService* svc2 = s2.get();
65 // By default, the singleton instance is constructed via new and
66 // deleted via delete, but this is configurable:
68 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
71 // Where create and destroy are functions, Singleton<T>::CreateFunc
72 // Singleton<T>::TeardownFunc.
74 // The above examples detail a situation where an expensive singleton is loaded
75 // on-demand (thus only if needed). However if there is an expensive singleton
76 // that will likely be needed, and initialization takes a potentially long time,
77 // e.g. while initializing, parsing some files, talking to remote services,
78 // making uses of other singletons, and so on, the initialization of those can
79 // be scheduled up front, or "eagerly".
81 // In that case the singleton can be declared this way:
84 // auto the_singleton =
85 // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
86 // .shouldEagerInit();
89 // This way the singleton's instance is built at program initialization,
90 // if the program opted-in to that feature by calling "doEagerInit" or
91 // "doEagerInitVia" during its startup.
93 // What if you need to destroy all of your singletons? Say, some of
94 // your singletons manage threads, but you need to fork? Or your unit
95 // test wants to clean up all global state? Then you can call
96 // SingletonVault::singleton()->destroyInstances(), which invokes the
97 // TeardownFunc for each singleton, in the reverse order they were
98 // created. It is your responsibility to ensure your singletons can
99 // handle cases where the singletons they depend on go away, however.
100 // Singletons won't be recreated after destroyInstances call. If you
101 // want to re-enable singleton creation (say after fork was called) you
102 // should call reenableInstances.
105 #include <folly/Baton.h>
106 #include <folly/Exception.h>
107 #include <folly/Hash.h>
108 #include <folly/Memory.h>
109 #include <folly/RWSpinLock.h>
110 #include <folly/Demangle.h>
111 #include <folly/Executor.h>
112 #include <folly/experimental/ReadMostlySharedPtr.h>
116 #include <condition_variable>
117 #include <functional>
124 #include <unordered_map>
125 #include <unordered_set>
128 #include <glog/logging.h>
130 // use this guard to handleSingleton breaking change in 3rd party code
131 #ifndef FOLLY_SINGLETON_TRY_GET
132 #define FOLLY_SINGLETON_TRY_GET
137 // For actual usage, please see the Singleton<T> class at the bottom
138 // of this file; that is what you will actually interact with.
140 // SingletonVault is the class that manages singleton instances. It
141 // is unaware of the underlying types of singletons, and simply
142 // manages lifecycles and invokes CreateFunc and TeardownFunc when
143 // appropriate. In general, you won't need to interact with the
144 // SingletonVault itself.
146 // A vault goes through a few stages of life:
148 // 1. Registration phase; singletons can be registered:
149 // a) Strict: no singleton can be created in this stage.
150 // b) Relaxed: singleton can be created (the default vault is Relaxed).
151 // 2. registrationComplete() has been called; singletons can no
152 // longer be registered, but they can be created.
153 // 3. A vault can return to stage 1 when destroyInstances is called.
155 // In general, you don't need to worry about any of the above; just
156 // ensure registrationComplete() is called near the top of your main()
157 // function, otherwise no singletons can be instantiated.
159 class SingletonVault;
163 // This internal-use-only class is used to create all leaked Meyers singletons.
164 // It guarantees that only one instance of every such singleton will ever be
165 // created, even when requested from different compilation units linked
167 class StaticSingletonManager {
169 static StaticSingletonManager& instance();
171 template <typename T, typename Tag, typename F>
172 inline T* create(F&& creator) {
173 auto& entry = [&]() mutable -> Entry<T>& {
174 std::lock_guard<std::mutex> lg(mutex_);
176 auto& id = typeid(TypePair<T, Tag>);
177 auto& entryPtr = reinterpret_cast<Entry<T>*&>(map_[id]);
179 entryPtr = new Entry<T>();
184 std::lock_guard<std::mutex> lg(entry.mutex);
187 entry.ptr = creator();
193 template <typename A, typename B>
196 StaticSingletonManager() {}
198 template <typename T>
204 std::unordered_map<std::type_index, intptr_t> map_;
208 template <typename T, typename Tag, typename F>
209 inline T* createGlobal(F&& creator) {
210 return StaticSingletonManager::instance().create<T, Tag>(
211 std::forward<F>(creator));
214 template <typename T, typename Tag>
215 inline T* createGlobal() {
216 return createGlobal<T, Tag>([]() { return new T(); });
219 struct DefaultTag {};
221 // A TypeDescriptor is the unique handle for a given singleton. It is
222 // a combinaiton of the type and of the optional name, and is used as
223 // a key in unordered_maps.
224 class TypeDescriptor {
226 TypeDescriptor(const std::type_info& ti,
227 const std::type_info& tag_ti)
228 : ti_(ti), tag_ti_(tag_ti) {
231 TypeDescriptor(const TypeDescriptor& other)
232 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
235 TypeDescriptor& operator=(const TypeDescriptor& other) {
236 if (this != &other) {
238 tag_ti_ = other.tag_ti_;
244 std::string name() const {
245 auto ret = demangle(ti_.name());
246 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
248 ret += demangle(tag_ti_.name());
250 return ret.toStdString();
253 friend class TypeDescriptorHasher;
255 bool operator==(const TypeDescriptor& other) const {
256 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
261 std::type_index tag_ti_;
264 class TypeDescriptorHasher {
266 size_t operator()(const TypeDescriptor& ti) const {
267 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
271 // This interface is used by SingletonVault to interact with SingletonHolders.
272 // Having a non-template interface allows SingletonVault to keep a list of all
274 class SingletonHolderBase {
276 virtual ~SingletonHolderBase() = default;
278 virtual TypeDescriptor type() = 0;
279 virtual bool hasLiveInstance() = 0;
280 virtual void createInstance() = 0;
281 virtual bool creationStarted() = 0;
282 virtual void destroyInstance() = 0;
285 static constexpr std::chrono::seconds kDestroyWaitTime{5};
288 // An actual instance of a singleton, tracking the instance itself,
289 // its state as described above, and the create and teardown
291 template <typename T>
292 struct SingletonHolder : public SingletonHolderBase {
294 typedef std::function<void(T*)> TeardownFunc;
295 typedef std::function<T*(void)> CreateFunc;
297 template <typename Tag, typename VaultTag>
298 inline static SingletonHolder<T>& singleton();
301 inline std::weak_ptr<T> get_weak();
302 inline std::shared_ptr<T> try_get();
303 inline folly::ReadMostlySharedPtr<T> try_get_fast();
305 void registerSingleton(CreateFunc c, TeardownFunc t);
306 void registerSingletonMock(CreateFunc c, TeardownFunc t);
307 virtual TypeDescriptor type() override;
308 virtual bool hasLiveInstance() override;
309 virtual void createInstance() override;
310 virtual bool creationStarted() override;
311 virtual void destroyInstance() override;
314 SingletonHolder(TypeDescriptor type, SingletonVault& vault);
316 enum class SingletonHolderState {
322 TypeDescriptor type_;
323 SingletonVault& vault_;
325 // mutex protects the entire entry during construction/destruction
328 // State of the singleton entry. If state is Living, instance_ptr and
329 // instance_weak can be safely accessed w/o synchronization.
330 std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
332 // the thread creating the singleton (only valid while creating an object)
333 std::atomic<std::thread::id> creating_thread_;
335 // The singleton itself and related functions.
337 // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
338 // from Dead to Living. Reset when state is changed from Living to Dead.
339 folly::ReadMostlyMainPtr<T> instance_;
340 // weak_ptr to the singleton instance, set when state is changed from Dead
341 // to Living. We never write to this object after initialization, so it is
342 // safe to read it from different threads w/o synchronization if we know
343 // that state is set to Living
344 std::weak_ptr<T> instance_weak_;
345 // Fast equivalent of instance_weak_
346 folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
347 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
348 std::shared_ptr<folly::Baton<>> destroy_baton_;
349 T* instance_ptr_ = nullptr;
350 CreateFunc create_ = nullptr;
351 TeardownFunc teardown_ = nullptr;
353 std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
355 SingletonHolder(const SingletonHolder&) = delete;
356 SingletonHolder& operator=(const SingletonHolder&) = delete;
357 SingletonHolder& operator=(SingletonHolder&&) = delete;
358 SingletonHolder(SingletonHolder&&) = delete;
363 class SingletonVault {
366 Strict, // Singletons can't be created before registrationComplete()
367 Relaxed, // Singletons can be created before registrationComplete()
371 * Clears all singletons in the given vault at ctor and dtor times.
372 * Useful for unit-tests that need to clear the world.
374 * This need can arise when a unit-test needs to swap out an object used by a
375 * singleton for a test-double, but the singleton needing its dependency to be
376 * swapped has a type or a tag local to some other translation unit and
377 * unavailable in the current translation unit.
379 * Other, better approaches to this need are "plz 2 refactor" ....
381 struct ScopedExpunger {
382 SingletonVault* vault;
383 explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
384 ~ScopedExpunger() { expunge(); }
386 vault->destroyInstances();
387 vault->reenableInstances();
391 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
393 // Destructor is only called by unit tests to check destroyInstances.
396 typedef std::function<void(void*)> TeardownFunc;
397 typedef std::function<void*(void)> CreateFunc;
399 // Ensure that Singleton has not been registered previously and that
400 // registration is not complete. If validations succeeds,
401 // register a singleton of a given type with the create and teardown
403 void registerSingleton(detail::SingletonHolderBase* entry);
406 * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
407 * is built when `doEagerInit[Via]` is called; see those methods
410 void addEagerInitSingleton(detail::SingletonHolderBase* entry);
412 // Mark registration is complete; no more singletons can be
413 // registered at this point.
414 void registrationComplete();
417 * Initialize all singletons which were marked as eager-initialized
418 * (using `shouldEagerInit()`). No return value. Propagates exceptions
419 * from constructors / create functions, as is the usual case when calling
420 * for example `Singleton<Foo>::get_weak()`.
425 * Schedule eager singletons' initializations through the given executor.
426 * If baton ptr is not null, its `post` method is called after all
427 * early initialization has completed.
429 * If exceptions are thrown during initialization, this method will still
430 * `post` the baton to indicate completion. The exception will not propagate
431 * and future attempts to `try_get` or `get_weak` the failed singleton will
432 * retry initialization.
436 * wangle::IOThreadPoolExecutor executor(max_concurrency_level);
437 * folly::Baton<> done;
438 * doEagerInitVia(executor, &done);
439 * done.wait(); // or 'timed_wait', or spin with 'try_wait'
442 void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
444 // Destroy all singletons; when complete, the vault can't create
445 // singletons once again until reenableInstances() is called.
446 void destroyInstances();
448 // Enable re-creating singletons after destroyInstances() was called.
449 void reenableInstances();
451 // For testing; how many registered and living singletons we have.
452 size_t registeredSingletonCount() const {
453 RWSpinLock::ReadHolder rh(&mutex_);
455 return singletons_.size();
459 * Flips to true if eager initialization was used, and has completed.
460 * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
462 bool eagerInitComplete() const;
464 size_t livingSingletonCount() const {
465 RWSpinLock::ReadHolder rh(&mutex_);
468 for (const auto& p : singletons_) {
469 if (p.second->hasLiveInstance()) {
477 // A well-known vault; you can actually have others, but this is the
479 static SingletonVault* singleton() {
480 return singleton<>();
483 // Gets singleton vault for any Tag. Non-default tag should be used in unit
485 template <typename VaultTag = detail::DefaultTag>
486 static SingletonVault* singleton() {
487 static SingletonVault* vault =
488 detail::createGlobal<SingletonVault, VaultTag>();
492 typedef std::string(*StackTraceGetterPtr)();
494 static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
495 static std::atomic<StackTraceGetterPtr>* stackTraceGetterPtr =
496 detail::createGlobal<std::atomic<StackTraceGetterPtr>,
498 return *stackTraceGetterPtr;
502 template <typename T>
503 friend struct detail::SingletonHolder;
505 // The two stages of life for a vault, as mentioned in the class comment.
506 enum class SingletonVaultState {
511 // Each singleton in the vault can be in two states: dead
512 // (registered but never created), living (CreateFunc returned an instance).
514 void stateCheck(SingletonVaultState expected,
515 const char* msg="Unexpected singleton state change") {
516 if (expected != state_) {
517 throw std::logic_error(msg);
521 // This method only matters if registrationComplete() is never called.
522 // Otherwise destroyInstances is scheduled to be executed atexit.
524 // Initializes static object, which calls destroyInstances on destruction.
525 // Used to have better deletion ordering with singleton not managed by
526 // folly::Singleton. The desruction will happen in the following order:
527 // 1. Singletons, not managed by folly::Singleton, which were created after
528 // any of the singletons managed by folly::Singleton was requested.
529 // 2. All singletons managed by folly::Singleton
530 // 3. Singletons, not managed by folly::Singleton, which were created before
531 // any of the singletons managed by folly::Singleton was requested.
532 static void scheduleDestroyInstances();
534 typedef std::unordered_map<detail::TypeDescriptor,
535 detail::SingletonHolderBase*,
536 detail::TypeDescriptorHasher> SingletonMap;
538 mutable folly::RWSpinLock mutex_;
539 SingletonMap singletons_;
540 std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
541 std::vector<detail::TypeDescriptor> creation_order_;
542 SingletonVaultState state_{SingletonVaultState::Running};
543 bool registrationComplete_{false};
544 folly::RWSpinLock stateMutex_;
545 Type type_{Type::Relaxed};
548 // This is the wrapper class that most users actually interact with.
549 // It allows for simple access to registering and instantiating
550 // singletons. Create instances of this class in the global scope of
551 // type Singleton<T> to register your singleton for later access via
552 // Singleton<T>::try_get().
553 template <typename T,
554 typename Tag = detail::DefaultTag,
555 typename VaultTag = detail::DefaultTag /* for testing */>
558 typedef std::function<T*(void)> CreateFunc;
559 typedef std::function<void(T*)> TeardownFunc;
561 // Generally your program life cycle should be fine with calling
562 // get() repeatedly rather than saving the reference, and then not
563 // call get() during process shutdown.
564 FOLLY_DEPRECATED("Replaced by try_get")
565 static T* get() { return getEntry().get(); }
567 // If, however, you do need to hold a reference to the specific
568 // singleton, you can try to do so with a weak_ptr. Avoid this when
569 // possible but the inability to lock the weak pointer can be a
570 // signal that the vault has been destroyed.
571 FOLLY_DEPRECATED("Replaced by try_get")
572 static std::weak_ptr<T> get_weak() { return getEntry().get_weak(); }
574 // Preferred alternative to get_weak, it returns shared_ptr that can be
575 // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
576 // Avoid holding these shared_ptrs beyond the scope of a function;
577 // don't put them in member variables, always use try_get() instead
579 // try_get() can return nullptr if the singleton was destroyed, caller is
580 // responsible for handling nullptr return
581 static std::shared_ptr<T> try_get() {
582 return getEntry().try_get();
585 static folly::ReadMostlySharedPtr<T> try_get_fast() {
586 return getEntry().try_get_fast();
589 explicit Singleton(std::nullptr_t /* _ */ = nullptr,
590 typename Singleton::TeardownFunc t = nullptr)
591 : Singleton([]() { return new T; }, std::move(t)) {}
593 explicit Singleton(typename Singleton::CreateFunc c,
594 typename Singleton::TeardownFunc t = nullptr) {
596 throw std::logic_error(
597 "nullptr_t should be passed if you want T to be default constructed");
600 auto vault = SingletonVault::singleton<VaultTag>();
601 getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
602 vault->registerSingleton(&getEntry());
606 * Should be instantiated as soon as "doEagerInit[Via]" is called.
607 * Singletons are usually lazy-loaded (built on-demand) but for those which
608 * are known to be needed, to avoid the potential lag for objects that take
609 * long to construct during runtime, there is an option to make sure these
610 * are built up-front.
613 * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
615 * Or alternately, define the singleton as usual, and say
616 * gFooInstance.shouldEagerInit();
618 * at some point prior to calling registrationComplete().
619 * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
621 Singleton& shouldEagerInit() {
622 auto vault = SingletonVault::singleton<VaultTag>();
623 vault->addEagerInitSingleton(&getEntry());
628 * Construct and inject a mock singleton which should be used only from tests.
629 * Unlike regular singletons which are initialized once per process lifetime,
630 * mock singletons live for the duration of a test. This means that one process
631 * running multiple tests can initialize and register the same singleton
632 * multiple times. This functionality should be used only from tests
633 * since it relaxes validation and performance in order to be able to perform
634 * the injection. The returned mock singleton is functionality identical to
635 * regular singletons.
637 static void make_mock(std::nullptr_t /* c */ = nullptr,
638 typename Singleton<T>::TeardownFunc t = nullptr) {
639 make_mock([]() { return new T; }, t);
642 static void make_mock(CreateFunc c,
643 typename Singleton<T>::TeardownFunc t = nullptr) {
645 throw std::logic_error(
646 "nullptr_t should be passed if you want T to be default constructed");
649 auto& entry = getEntry();
651 entry.registerSingletonMock(c, getTeardownFunc(t));
655 inline static detail::SingletonHolder<T>& getEntry() {
656 return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
659 // Construct TeardownFunc.
660 static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
663 return [](T* v) { delete v; };
670 template <typename T, typename Tag = detail::DefaultTag>
671 class LeakySingleton {
673 using CreateFunc = std::function<T*()>;
675 LeakySingleton() : LeakySingleton([] { return new T(); }) {}
677 explicit LeakySingleton(CreateFunc createFunc) {
678 auto& entry = entryInstance();
679 if (entry.state != State::NotRegistered) {
680 LOG(FATAL) << "Double registration of singletons of the same "
681 << "underlying type; check for multiple definitions "
682 << "of type folly::LeakySingleton<" + entry.type_.name() + ">";
684 entry.createFunc = createFunc;
685 entry.state = State::Dead;
688 static T& get() { return instance(); }
691 enum class State { NotRegistered, Dead, Living };
695 Entry(const Entry&) = delete;
696 Entry& operator=(const Entry&) = delete;
698 std::atomic<State> state{State::NotRegistered};
700 CreateFunc createFunc;
702 detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
705 static Entry& entryInstance() {
706 static auto entry = detail::createGlobal<Entry, Tag>();
710 static T& instance() {
711 auto& entry = entryInstance();
712 if (UNLIKELY(entry.state != State::Living)) {
719 static void createInstance() {
720 auto& entry = entryInstance();
722 std::lock_guard<std::mutex> lg(entry.mutex);
723 if (entry.state == State::Living) {
727 if (entry.state == State::NotRegistered) {
728 auto ptr = SingletonVault::stackTraceGetter().load();
729 LOG(FATAL) << "Creating instance for unregistered singleton: "
730 << entry.type_.name() << "\n"
732 << "\n" << (ptr ? (*ptr)() : "(not available)");
735 entry.ptr = entry.createFunc();
736 entry.state = State::Living;
741 #include <folly/Singleton-inl.h>