2 * Copyright 2014 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 // Within same compilation unit you should directly access it by the variable
38 // defining the singleton via get_fast()/get_weak_fast(), and even treat that
39 // variable like a smart pointer (dereferencing it or using the -> operator):
41 // MyExpensiveService* instance = the_singleton.get_fast();
43 // std::weak_ptr<MyExpensiveService> instance = the_singleton.get_weak_fast();
45 // the_singleton->doSomething();
47 // *_fast() accessors are faster than static accessors, and have performance
48 // similar to Meyers singletons/static objects.
50 // Please note, however, that all non-weak_ptr interfaces are
51 // inherently subject to races with destruction. Use responsibly.
53 // The singleton will be created on demand. If the constructor for
54 // MyExpensiveService actually makes use of *another* Singleton, then
55 // the right thing will happen -- that other singleton will complete
56 // construction before get() returns. However, in the event of a
57 // circular dependency, a runtime error will occur.
59 // You can have multiple singletons of the same underlying type, but
60 // each must be given a unique tag. If no tag is specified - default tag is used
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_fast();
71 // MyExpensiveService* svc1 = s1.get_fast();
72 // MyExpensiveService* svc2 = s2.get_fast();
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 // What if you need to destroy all of your singletons? Say, some of
84 // your singletons manage threads, but you need to fork? Or your unit
85 // test wants to clean up all global state? Then you can call
86 // SingletonVault::singleton()->destroyInstances(), which invokes the
87 // TeardownFunc for each singleton, in the reverse order they were
88 // created. It is your responsibility to ensure your singletons can
89 // handle cases where the singletons they depend on go away, however.
90 // Singletons won't be recreated after destroyInstances call. If you
91 // want to re-enable singleton creation (say after fork was called) you
92 // should call reenableInstances.
95 #include <folly/Baton.h>
96 #include <folly/Exception.h>
97 #include <folly/Hash.h>
98 #include <folly/Memory.h>
99 #include <folly/RWSpinLock.h>
100 #include <folly/Demangle.h>
101 #include <folly/io/async/Request.h>
107 #include <condition_variable>
109 #include <unordered_map>
110 #include <functional>
114 #include <glog/logging.h>
118 // For actual usage, please see the Singleton<T> class at the bottom
119 // of this file; that is what you will actually interact with.
121 // SingletonVault is the class that manages singleton instances. It
122 // is unaware of the underlying types of singletons, and simply
123 // manages lifecycles and invokes CreateFunc and TeardownFunc when
124 // appropriate. In general, you won't need to interact with the
125 // SingletonVault itself.
127 // A vault goes through a few stages of life:
129 // 1. Registration phase; singletons can be registered, but no
130 // singleton can be created.
131 // 2. registrationComplete() has been called; singletons can no
132 // longer be registered, but they can be created.
133 // 3. A vault can return to stage 1 when destroyInstances is called.
135 // In general, you don't need to worry about any of the above; just
136 // ensure registrationComplete() is called near the top of your main()
137 // function, otherwise no singletons can be instantiated.
141 struct DefaultTag {};
143 // A TypeDescriptor is the unique handle for a given singleton. It is
144 // a combinaiton of the type and of the optional name, and is used as
145 // a key in unordered_maps.
146 class TypeDescriptor {
148 TypeDescriptor(const std::type_info& ti,
149 const std::type_info& tag_ti)
150 : ti_(ti), tag_ti_(tag_ti) {
153 TypeDescriptor(const TypeDescriptor& other)
154 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
157 TypeDescriptor& operator=(const TypeDescriptor& other) {
158 if (this != &other) {
160 tag_ti_ = other.tag_ti_;
166 std::string prettyName() const {
167 auto ret = demangle(ti_.name());
168 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
170 ret += demangle(tag_ti_.name());
172 return ret.toStdString();
175 friend class TypeDescriptorHasher;
177 bool operator==(const TypeDescriptor& other) const {
178 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
183 std::type_index tag_ti_;
186 class TypeDescriptorHasher {
188 size_t operator()(const TypeDescriptor& ti) const {
189 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
193 enum class SingletonEntryState {
198 // An actual instance of a singleton, tracking the instance itself,
199 // its state as described above, and the create and teardown
201 struct SingletonEntry {
202 typedef std::function<void(void*)> TeardownFunc;
203 typedef std::function<void*(void)> CreateFunc;
205 SingletonEntry(CreateFunc c, TeardownFunc t) :
206 create(std::move(c)), teardown(std::move(t)) {}
208 // mutex protects the entire entry during construction/destruction
211 // State of the singleton entry. If state is Living, instance_ptr and
212 // instance_weak can be safely accessed w/o synchronization.
213 std::atomic<SingletonEntryState> state{SingletonEntryState::Dead};
215 // the thread creating the singleton (only valid while creating an object)
216 std::thread::id creating_thread;
218 // The singleton itself and related functions.
220 // holds a shared_ptr to singleton instance, set when state is changed from
221 // Dead to Living. Reset when state is changed from Living to Dead.
222 std::shared_ptr<void> instance;
223 // weak_ptr to the singleton instance, set when state is changed from Dead
224 // to Living. We never write to this object after initialization, so it is
225 // safe to read it from different threads w/o synchronization if we know
226 // that state is set to Living
227 std::weak_ptr<void> instance_weak;
228 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
229 std::shared_ptr<folly::Baton<>> destroy_baton;
230 void* instance_ptr = nullptr;
231 CreateFunc create = nullptr;
232 TeardownFunc teardown = nullptr;
234 SingletonEntry(const SingletonEntry&) = delete;
235 SingletonEntry& operator=(const SingletonEntry&) = delete;
236 SingletonEntry& operator=(SingletonEntry&&) = delete;
237 SingletonEntry(SingletonEntry&&) = delete;
242 class SingletonVault {
244 enum class Type { Strict, Relaxed };
246 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
248 // Destructor is only called by unit tests to check destroyInstances.
251 typedef std::function<void(void*)> TeardownFunc;
252 typedef std::function<void*(void)> CreateFunc;
254 // Ensure that Singleton has not been registered previously and that
255 // registration is not complete. If validations succeeds,
256 // register a singleton of a given type with the create and teardown
258 detail::SingletonEntry& registerSingleton(detail::TypeDescriptor type,
260 TeardownFunc teardown) {
261 RWSpinLock::ReadHolder rh(&stateMutex_);
263 stateCheck(SingletonVaultState::Running);
265 if (UNLIKELY(registrationComplete_)) {
266 throw std::logic_error(
267 "Registering singleton after registrationComplete().");
270 RWSpinLock::ReadHolder rhMutex(&mutex_);
271 CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
273 return registerSingletonImpl(type, create, teardown);
276 // Register a singleton of a given type with the create and teardown
277 // functions. Must hold reader locks on stateMutex_ and mutex_
278 // when invoking this function.
279 detail::SingletonEntry& registerSingletonImpl(detail::TypeDescriptor type,
281 TeardownFunc teardown) {
282 RWSpinLock::UpgradedHolder wh(&mutex_);
285 folly::make_unique<detail::SingletonEntry>(std::move(create),
286 std::move(teardown));
287 return *singletons_[type];
290 /* Register a mock singleton used for testing of singletons which
291 * depend on other private singletons which cannot be otherwise injected.
293 void registerMockSingleton(detail::TypeDescriptor type,
295 TeardownFunc teardown) {
296 RWSpinLock::ReadHolder rh(&stateMutex_);
297 RWSpinLock::ReadHolder rhMutex(&mutex_);
299 auto entry_it = singletons_.find(type);
300 // Mock singleton registration, we allow existing entry to be overridden.
301 if (entry_it == singletons_.end()) {
302 throw std::logic_error(
303 "Registering mock before the singleton was registered");
307 auto& entry = *(entry_it->second);
308 // Destroy existing singleton.
309 std::lock_guard<std::mutex> entry_lg(entry.mutex);
311 destroyInstance(entry_it);
312 entry.create = create;
313 entry.teardown = teardown;
316 // Upgrade to write lock.
317 RWSpinLock::UpgradedHolder whMutex(&mutex_);
319 // Remove singleton from creation order and singletons_.
320 // This happens only in test code and not frequently.
321 // Performance is not a concern here.
322 auto creation_order_it = std::find(
323 creation_order_.begin(),
324 creation_order_.end(),
326 if (creation_order_it != creation_order_.end()) {
327 creation_order_.erase(creation_order_it);
331 // Mark registration is complete; no more singletons can be
332 // registered at this point.
333 void registrationComplete() {
334 RequestContext::getStaticContext();
335 std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
337 RWSpinLock::WriteHolder wh(&stateMutex_);
339 stateCheck(SingletonVaultState::Running);
341 if (type_ == Type::Strict) {
342 for (const auto& id_singleton_entry: singletons_) {
343 const auto& singleton_entry = *id_singleton_entry.second;
344 if (singleton_entry.state != detail::SingletonEntryState::Dead) {
345 throw std::runtime_error(
346 "Singleton created before registration was complete.");
351 registrationComplete_ = true;
354 // Destroy all singletons; when complete, the vault can't create
355 // singletons once again until reenableInstances() is called.
356 void destroyInstances();
358 // Enable re-creating singletons after destroyInstances() was called.
359 void reenableInstances();
361 // Retrieve a singleton from the vault, creating it if necessary.
362 std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
363 auto entry = get_entry_create(type);
364 return entry->instance_weak;
367 // This function is inherently racy since we don't hold the
368 // shared_ptr that contains the Singleton. It is the caller's
369 // responsibility to be sane with this, but it is preferable to use
370 // the weak_ptr interface for true safety.
371 void* get_ptr(detail::TypeDescriptor type) {
372 auto entry = get_entry_create(type);
373 if (UNLIKELY(entry->instance_weak.expired())) {
374 throw std::runtime_error(
375 "Raw pointer to a singleton requested after its destruction.");
377 return entry->instance_ptr;
380 // For testing; how many registered and living singletons we have.
381 size_t registeredSingletonCount() const {
382 RWSpinLock::ReadHolder rh(&mutex_);
384 return singletons_.size();
387 size_t livingSingletonCount() const {
388 RWSpinLock::ReadHolder rh(&mutex_);
391 for (const auto& p : singletons_) {
392 if (p.second->state == detail::SingletonEntryState::Living) {
400 // A well-known vault; you can actually have others, but this is the
402 static SingletonVault* singleton();
405 // The two stages of life for a vault, as mentioned in the class comment.
406 enum class SingletonVaultState {
411 // Each singleton in the vault can be in two states: dead
412 // (registered but never created), living (CreateFunc returned an instance).
414 void stateCheck(SingletonVaultState expected,
415 const char* msg="Unexpected singleton state change") {
416 if (expected != state_) {
417 throw std::logic_error(msg);
421 // This method only matters if registrationComplete() is never called.
422 // Otherwise destroyInstances is scheduled to be executed atexit.
424 // Initializes static object, which calls destroyInstances on destruction.
425 // Used to have better deletion ordering with singleton not managed by
426 // folly::Singleton. The desruction will happen in the following order:
427 // 1. Singletons, not managed by folly::Singleton, which were created after
428 // any of the singletons managed by folly::Singleton was requested.
429 // 2. All singletons managed by folly::Singleton
430 // 3. Singletons, not managed by folly::Singleton, which were created before
431 // any of the singletons managed by folly::Singleton was requested.
432 static void scheduleDestroyInstances();
434 detail::SingletonEntry* get_entry(detail::TypeDescriptor type) {
435 RWSpinLock::ReadHolder rh(&mutex_);
437 auto it = singletons_.find(type);
438 if (it == singletons_.end()) {
439 throw std::out_of_range(std::string("non-existent singleton: ") +
443 return it->second.get();
446 // Get a pointer to the living SingletonEntry for the specified
447 // type. The singleton is created as part of this function, if
449 detail::SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
450 auto entry = get_entry(type);
452 if (LIKELY(entry->state == detail::SingletonEntryState::Living)) {
456 // There's no synchronization here, so we may not see the current value
457 // for creating_thread if it was set by other thread, but we only care about
458 // it if it was set by current thread anyways.
459 if (entry->creating_thread == std::this_thread::get_id()) {
460 throw std::out_of_range(std::string("circular singleton dependency: ") +
464 std::lock_guard<std::mutex> entry_lock(entry->mutex);
466 if (entry->state == detail::SingletonEntryState::Living) {
470 entry->creating_thread = std::this_thread::get_id();
472 RWSpinLock::ReadHolder rh(&stateMutex_);
473 if (state_ == SingletonVaultState::Quiescing) {
474 entry->creating_thread = std::thread::id();
478 auto destroy_baton = std::make_shared<folly::Baton<>>();
479 auto teardown = entry->teardown;
481 // Can't use make_shared -- no support for a custom deleter, sadly.
482 auto instance = std::shared_ptr<void>(
484 [destroy_baton, teardown](void* instance_ptr) mutable {
485 teardown(instance_ptr);
486 destroy_baton->post();
489 // We should schedule destroyInstances() only after the singleton was
490 // created. This will ensure it will be destroyed before singletons,
491 // not managed by folly::Singleton, which were initialized in its
493 scheduleDestroyInstances();
495 entry->instance = instance;
496 entry->instance_weak = instance;
497 entry->instance_ptr = instance.get();
498 entry->creating_thread = std::thread::id();
499 entry->destroy_baton = std::move(destroy_baton);
501 // This has to be the last step, because once state is Living other threads
502 // may access instance and instance_weak w/o synchronization.
503 entry->state.store(detail::SingletonEntryState::Living);
506 RWSpinLock::WriteHolder wh(&mutex_);
507 creation_order_.push_back(type);
512 typedef std::unique_ptr<detail::SingletonEntry> SingletonEntryPtr;
513 typedef std::unordered_map<detail::TypeDescriptor,
515 detail::TypeDescriptorHasher> SingletonMap;
517 /* Destroy and clean-up one singleton. Must be invoked while holding
518 * a read lock on mutex_.
519 * @param typeDescriptor - the type key for the removed singleton.
521 void destroyInstance(SingletonMap::iterator entry_it);
523 mutable folly::RWSpinLock mutex_;
524 SingletonMap singletons_;
525 std::vector<detail::TypeDescriptor> creation_order_;
526 SingletonVaultState state_{SingletonVaultState::Running};
527 bool registrationComplete_{false};
528 folly::RWSpinLock stateMutex_;
529 Type type_{Type::Relaxed};
532 // This is the wrapper class that most users actually interact with.
533 // It allows for simple access to registering and instantiating
534 // singletons. Create instances of this class in the global scope of
535 // type Singleton<T> to register your singleton for later access via
536 // Singleton<T>::get().
537 template <typename T, typename Tag = detail::DefaultTag>
540 typedef std::function<T*(void)> CreateFunc;
541 typedef std::function<void(T*)> TeardownFunc;
543 // Generally your program life cycle should be fine with calling
544 // get() repeatedly rather than saving the reference, and then not
545 // call get() during process shutdown.
546 static T* get(SingletonVault* vault = nullptr /* for testing */) {
547 return static_cast<T*>(
548 (vault ?: SingletonVault::singleton())->get_ptr(typeDescriptor()));
551 // Same as get, but should be preffered to it in the same compilation
552 // unit, where Singleton is registered.
554 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
555 return reinterpret_cast<T*>(entry_->instance_ptr);
561 // If, however, you do need to hold a reference to the specific
562 // singleton, you can try to do so with a weak_ptr. Avoid this when
563 // possible but the inability to lock the weak pointer can be a
564 // signal that the vault has been destroyed.
565 static std::weak_ptr<T> get_weak(
566 SingletonVault* vault = nullptr /* for testing */) {
568 (vault ?: SingletonVault::singleton())->get_weak(typeDescriptor());
570 // This is ugly and inefficient, but there's no other way to do it, because
571 // there's no static_pointer_cast for weak_ptr.
572 auto shared_void_ptr = weak_void_ptr.lock();
573 if (!shared_void_ptr) {
574 return std::weak_ptr<T>();
576 return std::static_pointer_cast<T>(shared_void_ptr);
579 // Same as get_weak, but should be preffered to it in the same compilation
580 // unit, where Singleton is registered.
581 std::weak_ptr<T> get_weak_fast() {
582 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
583 // This is ugly and inefficient, but there's no other way to do it,
584 // because there's no static_pointer_cast for weak_ptr.
585 auto shared_void_ptr = entry_->instance_weak.lock();
586 if (!shared_void_ptr) {
587 return std::weak_ptr<T>();
589 return std::static_pointer_cast<T>(shared_void_ptr);
591 return get_weak(vault_);
595 // Allow the Singleton<t> instance to also retrieve the underlying
596 // singleton, if desired.
597 T* ptr() { return get_fast(); }
598 T& operator*() { return *ptr(); }
599 T* operator->() { return ptr(); }
601 explicit Singleton(std::nullptr_t _ = nullptr,
602 Singleton::TeardownFunc t = nullptr,
603 SingletonVault* vault = nullptr) :
604 Singleton ([]() { return new T; },
609 explicit Singleton(Singleton::CreateFunc c,
610 Singleton::TeardownFunc t = nullptr,
611 SingletonVault* vault = nullptr) {
613 throw std::logic_error(
614 "nullptr_t should be passed if you want T to be default constructed");
617 if (vault == nullptr) {
618 vault = SingletonVault::singleton();
623 &(vault->registerSingleton(typeDescriptor(), c, getTeardownFunc(t)));
627 * Construct and inject a mock singleton which should be used only from tests.
628 * Unlike regular singletons which are initialized once per process lifetime,
629 * mock singletons live for the duration of a test. This means that one process
630 * running multiple tests can initialize and register the same singleton
631 * multiple times. This functionality should be used only from tests
632 * since it relaxes validation and performance in order to be able to perform
633 * the injection. The returned mock singleton is functionality identical to
634 * regular singletons.
636 static void make_mock(std::nullptr_t c = nullptr,
637 typename Singleton<T>::TeardownFunc t = nullptr,
638 SingletonVault* vault = nullptr /* for testing */ ) {
639 make_mock([]() { return new T; }, t, vault);
642 static void make_mock(CreateFunc c,
643 typename Singleton<T>::TeardownFunc t = nullptr,
644 SingletonVault* vault = nullptr /* for testing */ ) {
646 throw std::logic_error(
647 "nullptr_t should be passed if you want T to be default constructed");
650 if (vault == nullptr) {
651 vault = SingletonVault::singleton();
654 vault->registerMockSingleton(
661 static detail::TypeDescriptor typeDescriptor() {
662 return {typeid(T), typeid(Tag)};
665 // Construct SingletonVault::TeardownFunc.
666 static SingletonVault::TeardownFunc getTeardownFunc(
668 SingletonVault::TeardownFunc teardown;
670 teardown = [](void* v) { delete static_cast<T*>(v); };
672 teardown = [t](void* v) { t(static_cast<T*>(v)); };
678 // This is pointing to SingletonEntry paired with this singleton object. This
679 // is never reset, so each SingletonEntry should never be destroyed.
680 // We rely on the fact that Singleton destructor won't reset this pointer, so
681 // it can be "safely" used even after static Singleton object is destroyed.
682 detail::SingletonEntry* entry_;
683 SingletonVault* vault_;