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/io/async/Request.h>
106 #include <condition_variable>
108 #include <unordered_map>
109 #include <functional>
113 #include <glog/logging.h>
117 // For actual usage, please see the Singleton<T> class at the bottom
118 // of this file; that is what you will actually interact with.
120 // SingletonVault is the class that manages singleton instances. It
121 // is unaware of the underlying types of singletons, and simply
122 // manages lifecycles and invokes CreateFunc and TeardownFunc when
123 // appropriate. In general, you won't need to interact with the
124 // SingletonVault itself.
126 // A vault goes through a few stages of life:
128 // 1. Registration phase; singletons can be registered, but no
129 // singleton can be created.
130 // 2. registrationComplete() has been called; singletons can no
131 // longer be registered, but they can be created.
132 // 3. A vault can return to stage 1 when destroyInstances is called.
134 // In general, you don't need to worry about any of the above; just
135 // ensure registrationComplete() is called near the top of your main()
136 // function, otherwise no singletons can be instantiated.
140 struct DefaultTag {};
142 // A TypeDescriptor is the unique handle for a given singleton. It is
143 // a combinaiton of the type and of the optional name, and is used as
144 // a key in unordered_maps.
145 class TypeDescriptor {
147 TypeDescriptor(const std::type_info& ti,
148 const std::type_info& tag_ti)
149 : ti_(ti), tag_ti_(tag_ti) {
152 TypeDescriptor(const TypeDescriptor& other)
153 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
156 TypeDescriptor& operator=(const TypeDescriptor& other) {
157 if (this != &other) {
159 tag_ti_ = other.tag_ti_;
165 std::string name() const {
166 std::string ret = ti_.name();
167 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
169 ret += tag_ti_.name();
174 friend class TypeDescriptorHasher;
176 bool operator==(const TypeDescriptor& other) const {
177 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
182 std::type_index tag_ti_;
185 class TypeDescriptorHasher {
187 size_t operator()(const TypeDescriptor& ti) const {
188 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
192 enum class SingletonEntryState {
197 // An actual instance of a singleton, tracking the instance itself,
198 // its state as described above, and the create and teardown
200 struct SingletonEntry {
201 typedef std::function<void(void*)> TeardownFunc;
202 typedef std::function<void*(void)> CreateFunc;
204 SingletonEntry(CreateFunc c, TeardownFunc t) :
205 create(std::move(c)), teardown(std::move(t)) {}
207 // mutex protects the entire entry during construction/destruction
210 // State of the singleton entry. If state is Living, instance_ptr and
211 // instance_weak can be safely accessed w/o synchronization.
212 std::atomic<SingletonEntryState> state{SingletonEntryState::Dead};
214 // the thread creating the singleton (only valid while creating an object)
215 std::thread::id creating_thread;
217 // The singleton itself and related functions.
219 // holds a shared_ptr to singleton instance, set when state is changed from
220 // Dead to Living. Reset when state is changed from Living to Dead.
221 std::shared_ptr<void> instance;
222 // weak_ptr to the singleton instance, set when state is changed from Dead
223 // to Living. We never write to this object after initialization, so it is
224 // safe to read it from different threads w/o synchronization if we know
225 // that state is set to Living
226 std::weak_ptr<void> instance_weak;
227 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
228 std::shared_ptr<folly::Baton<>> destroy_baton;
229 void* instance_ptr = nullptr;
230 CreateFunc create = nullptr;
231 TeardownFunc teardown = nullptr;
233 SingletonEntry(const SingletonEntry&) = delete;
234 SingletonEntry& operator=(const SingletonEntry&) = delete;
235 SingletonEntry& operator=(SingletonEntry&&) = delete;
236 SingletonEntry(SingletonEntry&&) = delete;
241 class SingletonVault {
243 enum class Type { Strict, Relaxed };
245 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
247 // Destructor is only called by unit tests to check destroyInstances.
250 typedef std::function<void(void*)> TeardownFunc;
251 typedef std::function<void*(void)> CreateFunc;
253 // Ensure that Singleton has not been registered previously and that
254 // registration is not complete. If validations succeeds,
255 // register a singleton of a given type with the create and teardown
257 detail::SingletonEntry& registerSingleton(detail::TypeDescriptor type,
259 TeardownFunc teardown) {
260 RWSpinLock::ReadHolder rh(&stateMutex_);
262 stateCheck(SingletonVaultState::Running);
264 if (UNLIKELY(registrationComplete_)) {
265 throw std::logic_error(
266 "Registering singleton after registrationComplete().");
269 RWSpinLock::ReadHolder rhMutex(&mutex_);
270 CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
272 return registerSingletonImpl(type, create, teardown);
275 // Register a singleton of a given type with the create and teardown
276 // functions. Must hold reader locks on stateMutex_ and mutex_
277 // when invoking this function.
278 detail::SingletonEntry& registerSingletonImpl(detail::TypeDescriptor type,
280 TeardownFunc teardown) {
281 RWSpinLock::UpgradedHolder wh(&mutex_);
284 folly::make_unique<detail::SingletonEntry>(std::move(create),
285 std::move(teardown));
286 return *singletons_[type];
289 /* Register a mock singleton used for testing of singletons which
290 * depend on other private singletons which cannot be otherwise injected.
292 void registerMockSingleton(detail::TypeDescriptor type,
294 TeardownFunc teardown) {
295 RWSpinLock::ReadHolder rh(&stateMutex_);
296 RWSpinLock::ReadHolder rhMutex(&mutex_);
298 auto entry_it = singletons_.find(type);
299 // Mock singleton registration, we allow existing entry to be overridden.
300 if (entry_it == singletons_.end()) {
301 throw std::logic_error(
302 "Registering mock before the singleton was registered");
306 auto& entry = *(entry_it->second);
307 // Destroy existing singleton.
308 std::lock_guard<std::mutex> entry_lg(entry.mutex);
310 destroyInstance(entry_it);
311 entry.create = create;
312 entry.teardown = teardown;
315 // Upgrade to write lock.
316 RWSpinLock::UpgradedHolder whMutex(&mutex_);
318 // Remove singleton from creation order and singletons_.
319 // This happens only in test code and not frequently.
320 // Performance is not a concern here.
321 auto creation_order_it = std::find(
322 creation_order_.begin(),
323 creation_order_.end(),
325 if (creation_order_it != creation_order_.end()) {
326 creation_order_.erase(creation_order_it);
330 // Mark registration is complete; no more singletons can be
331 // registered at this point.
332 void registrationComplete() {
333 RequestContext::getStaticContext();
334 std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
336 RWSpinLock::WriteHolder wh(&stateMutex_);
338 stateCheck(SingletonVaultState::Running);
340 if (type_ == Type::Strict) {
341 for (const auto& id_singleton_entry: singletons_) {
342 const auto& singleton_entry = *id_singleton_entry.second;
343 if (singleton_entry.state != detail::SingletonEntryState::Dead) {
344 throw std::runtime_error(
345 "Singleton created before registration was complete.");
350 registrationComplete_ = true;
353 // Destroy all singletons; when complete, the vault can't create
354 // singletons once again until reenableInstances() is called.
355 void destroyInstances();
357 // Enable re-creating singletons after destroyInstances() was called.
358 void reenableInstances();
360 // Retrieve a singleton from the vault, creating it if necessary.
361 std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
362 auto entry = get_entry_create(type);
363 return entry->instance_weak;
366 // This function is inherently racy since we don't hold the
367 // shared_ptr that contains the Singleton. It is the caller's
368 // responsibility to be sane with this, but it is preferable to use
369 // the weak_ptr interface for true safety.
370 void* get_ptr(detail::TypeDescriptor type) {
371 auto entry = get_entry_create(type);
372 if (UNLIKELY(entry->instance_weak.expired())) {
373 throw std::runtime_error(
374 "Raw pointer to a singleton requested after its destruction.");
376 return entry->instance_ptr;
379 // For testing; how many registered and living singletons we have.
380 size_t registeredSingletonCount() const {
381 RWSpinLock::ReadHolder rh(&mutex_);
383 return singletons_.size();
386 size_t livingSingletonCount() const {
387 RWSpinLock::ReadHolder rh(&mutex_);
390 for (const auto& p : singletons_) {
391 if (p.second->state == detail::SingletonEntryState::Living) {
399 // A well-known vault; you can actually have others, but this is the
401 static SingletonVault* singleton();
404 // The two stages of life for a vault, as mentioned in the class comment.
405 enum class SingletonVaultState {
410 // Each singleton in the vault can be in two states: dead
411 // (registered but never created), living (CreateFunc returned an instance).
413 void stateCheck(SingletonVaultState expected,
414 const char* msg="Unexpected singleton state change") {
415 if (expected != state_) {
416 throw std::logic_error(msg);
420 // This method only matters if registrationComplete() is never called.
421 // Otherwise destroyInstances is scheduled to be executed atexit.
423 // Initializes static object, which calls destroyInstances on destruction.
424 // Used to have better deletion ordering with singleton not managed by
425 // folly::Singleton. The desruction will happen in the following order:
426 // 1. Singletons, not managed by folly::Singleton, which were created after
427 // any of the singletons managed by folly::Singleton was requested.
428 // 2. All singletons managed by folly::Singleton
429 // 3. Singletons, not managed by folly::Singleton, which were created before
430 // any of the singletons managed by folly::Singleton was requested.
431 static void scheduleDestroyInstances();
433 detail::SingletonEntry* get_entry(detail::TypeDescriptor type) {
434 RWSpinLock::ReadHolder rh(&mutex_);
436 auto it = singletons_.find(type);
437 if (it == singletons_.end()) {
438 throw std::out_of_range(std::string("non-existent singleton: ") +
442 return it->second.get();
445 // Get a pointer to the living SingletonEntry for the specified
446 // type. The singleton is created as part of this function, if
448 detail::SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
449 auto entry = get_entry(type);
451 if (LIKELY(entry->state == detail::SingletonEntryState::Living)) {
455 // There's no synchronization here, so we may not see the current value
456 // for creating_thread if it was set by other thread, but we only care about
457 // it if it was set by current thread anyways.
458 if (entry->creating_thread == std::this_thread::get_id()) {
459 throw std::out_of_range(std::string("circular singleton dependency: ") +
463 std::lock_guard<std::mutex> entry_lock(entry->mutex);
465 if (entry->state == detail::SingletonEntryState::Living) {
469 entry->creating_thread = std::this_thread::get_id();
471 RWSpinLock::ReadHolder rh(&stateMutex_);
472 if (state_ == SingletonVaultState::Quiescing) {
473 entry->creating_thread = std::thread::id();
477 auto destroy_baton = std::make_shared<folly::Baton<>>();
478 auto teardown = entry->teardown;
480 // Can't use make_shared -- no support for a custom deleter, sadly.
481 auto instance = std::shared_ptr<void>(
483 [destroy_baton, teardown](void* instance_ptr) mutable {
484 teardown(instance_ptr);
485 destroy_baton->post();
488 // We should schedule destroyInstances() only after the singleton was
489 // created. This will ensure it will be destroyed before singletons,
490 // not managed by folly::Singleton, which were initialized in its
492 scheduleDestroyInstances();
494 entry->instance = instance;
495 entry->instance_weak = instance;
496 entry->instance_ptr = instance.get();
497 entry->creating_thread = std::thread::id();
498 entry->destroy_baton = std::move(destroy_baton);
500 // This has to be the last step, because once state is Living other threads
501 // may access instance and instance_weak w/o synchronization.
502 entry->state.store(detail::SingletonEntryState::Living);
505 RWSpinLock::WriteHolder wh(&mutex_);
506 creation_order_.push_back(type);
511 typedef std::unique_ptr<detail::SingletonEntry> SingletonEntryPtr;
512 typedef std::unordered_map<detail::TypeDescriptor,
514 detail::TypeDescriptorHasher> SingletonMap;
516 /* Destroy and clean-up one singleton. Must be invoked while holding
517 * a read lock on mutex_.
518 * @param typeDescriptor - the type key for the removed singleton.
520 void destroyInstance(SingletonMap::iterator entry_it);
522 mutable folly::RWSpinLock mutex_;
523 SingletonMap singletons_;
524 std::vector<detail::TypeDescriptor> creation_order_;
525 SingletonVaultState state_{SingletonVaultState::Running};
526 bool registrationComplete_{false};
527 folly::RWSpinLock stateMutex_;
528 Type type_{Type::Relaxed};
531 // This is the wrapper class that most users actually interact with.
532 // It allows for simple access to registering and instantiating
533 // singletons. Create instances of this class in the global scope of
534 // type Singleton<T> to register your singleton for later access via
535 // Singleton<T>::get().
536 template <typename T, typename Tag = detail::DefaultTag>
539 typedef std::function<T*(void)> CreateFunc;
540 typedef std::function<void(T*)> TeardownFunc;
542 // Generally your program life cycle should be fine with calling
543 // get() repeatedly rather than saving the reference, and then not
544 // call get() during process shutdown.
545 static T* get(SingletonVault* vault = nullptr /* for testing */) {
546 return static_cast<T*>(
547 (vault ?: SingletonVault::singleton())->get_ptr(typeDescriptor()));
550 // Same as get, but should be preffered to it in the same compilation
551 // unit, where Singleton is registered.
553 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
554 return reinterpret_cast<T*>(entry_->instance_ptr);
560 // If, however, you do need to hold a reference to the specific
561 // singleton, you can try to do so with a weak_ptr. Avoid this when
562 // possible but the inability to lock the weak pointer can be a
563 // signal that the vault has been destroyed.
564 static std::weak_ptr<T> get_weak(
565 SingletonVault* vault = nullptr /* for testing */) {
567 (vault ?: SingletonVault::singleton())->get_weak(typeDescriptor());
569 // This is ugly and inefficient, but there's no other way to do it, because
570 // there's no static_pointer_cast for weak_ptr.
571 auto shared_void_ptr = weak_void_ptr.lock();
572 if (!shared_void_ptr) {
573 return std::weak_ptr<T>();
575 return std::static_pointer_cast<T>(shared_void_ptr);
578 // Same as get_weak, but should be preffered to it in the same compilation
579 // unit, where Singleton is registered.
580 std::weak_ptr<T> get_weak_fast() {
581 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
582 // This is ugly and inefficient, but there's no other way to do it,
583 // because there's no static_pointer_cast for weak_ptr.
584 auto shared_void_ptr = entry_->instance_weak.lock();
585 if (!shared_void_ptr) {
586 return std::weak_ptr<T>();
588 return std::static_pointer_cast<T>(shared_void_ptr);
590 return get_weak(vault_);
594 // Allow the Singleton<t> instance to also retrieve the underlying
595 // singleton, if desired.
596 T* ptr() { return get_fast(); }
597 T& operator*() { return *ptr(); }
598 T* operator->() { return ptr(); }
600 explicit Singleton(std::nullptr_t _ = nullptr,
601 Singleton::TeardownFunc t = nullptr,
602 SingletonVault* vault = nullptr) :
603 Singleton ([]() { return new T; },
608 explicit Singleton(Singleton::CreateFunc c,
609 Singleton::TeardownFunc t = nullptr,
610 SingletonVault* vault = nullptr) {
612 throw std::logic_error(
613 "nullptr_t should be passed if you want T to be default constructed");
616 if (vault == nullptr) {
617 vault = SingletonVault::singleton();
622 &(vault->registerSingleton(typeDescriptor(), c, getTeardownFunc(t)));
626 * Construct and inject a mock singleton which should be used only from tests.
627 * Unlike regular singletons which are initialized once per process lifetime,
628 * mock singletons live for the duration of a test. This means that one process
629 * running multiple tests can initialize and register the same singleton
630 * multiple times. This functionality should be used only from tests
631 * since it relaxes validation and performance in order to be able to perform
632 * the injection. The returned mock singleton is functionality identical to
633 * regular singletons.
635 static void make_mock(std::nullptr_t c = nullptr,
636 typename Singleton<T>::TeardownFunc t = nullptr,
637 SingletonVault* vault = nullptr /* for testing */ ) {
638 make_mock([]() { return new T; }, t, vault);
641 static void make_mock(CreateFunc c,
642 typename Singleton<T>::TeardownFunc t = nullptr,
643 SingletonVault* vault = nullptr /* for testing */ ) {
645 throw std::logic_error(
646 "nullptr_t should be passed if you want T to be default constructed");
649 if (vault == nullptr) {
650 vault = SingletonVault::singleton();
653 vault->registerMockSingleton(
660 static detail::TypeDescriptor typeDescriptor() {
661 return {typeid(T), typeid(Tag)};
664 // Construct SingletonVault::TeardownFunc.
665 static SingletonVault::TeardownFunc getTeardownFunc(
667 SingletonVault::TeardownFunc teardown;
669 teardown = [](void* v) { delete static_cast<T*>(v); };
671 teardown = [t](void* v) { t(static_cast<T*>(v)); };
677 // This is pointing to SingletonEntry paired with this singleton object. This
678 // is never reset, so each SingletonEntry should never be destroyed.
679 // We rely on the fact that Singleton destructor won't reset this pointer, so
680 // it can be "safely" used even after static Singleton object is destroyed.
681 detail::SingletonEntry* entry_;
682 SingletonVault* vault_;