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() {
403 return singleton<>();
406 // Gets singleton vault for any Tag. Non-default tag should be used in unit
408 template <typename VaultTag = detail::DefaultTag>
409 static SingletonVault* singleton() {
410 static SingletonVault* vault = new SingletonVault();
415 // The two stages of life for a vault, as mentioned in the class comment.
416 enum class SingletonVaultState {
421 // Each singleton in the vault can be in two states: dead
422 // (registered but never created), living (CreateFunc returned an instance).
424 void stateCheck(SingletonVaultState expected,
425 const char* msg="Unexpected singleton state change") {
426 if (expected != state_) {
427 throw std::logic_error(msg);
431 // This method only matters if registrationComplete() is never called.
432 // Otherwise destroyInstances is scheduled to be executed atexit.
434 // Initializes static object, which calls destroyInstances on destruction.
435 // Used to have better deletion ordering with singleton not managed by
436 // folly::Singleton. The desruction will happen in the following order:
437 // 1. Singletons, not managed by folly::Singleton, which were created after
438 // any of the singletons managed by folly::Singleton was requested.
439 // 2. All singletons managed by folly::Singleton
440 // 3. Singletons, not managed by folly::Singleton, which were created before
441 // any of the singletons managed by folly::Singleton was requested.
442 static void scheduleDestroyInstances();
444 detail::SingletonEntry* get_entry(detail::TypeDescriptor type) {
445 RWSpinLock::ReadHolder rh(&mutex_);
447 auto it = singletons_.find(type);
448 if (it == singletons_.end()) {
449 throw std::out_of_range(std::string("non-existent singleton: ") +
453 return it->second.get();
456 // Get a pointer to the living SingletonEntry for the specified
457 // type. The singleton is created as part of this function, if
459 detail::SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
460 auto entry = get_entry(type);
462 if (LIKELY(entry->state == detail::SingletonEntryState::Living)) {
466 // There's no synchronization here, so we may not see the current value
467 // for creating_thread if it was set by other thread, but we only care about
468 // it if it was set by current thread anyways.
469 if (entry->creating_thread == std::this_thread::get_id()) {
470 throw std::out_of_range(std::string("circular singleton dependency: ") +
474 std::lock_guard<std::mutex> entry_lock(entry->mutex);
476 if (entry->state == detail::SingletonEntryState::Living) {
480 entry->creating_thread = std::this_thread::get_id();
482 RWSpinLock::ReadHolder rh(&stateMutex_);
483 if (state_ == SingletonVaultState::Quiescing) {
484 entry->creating_thread = std::thread::id();
488 auto destroy_baton = std::make_shared<folly::Baton<>>();
489 auto teardown = entry->teardown;
491 // Can't use make_shared -- no support for a custom deleter, sadly.
492 auto instance = std::shared_ptr<void>(
494 [destroy_baton, teardown](void* instance_ptr) mutable {
495 teardown(instance_ptr);
496 destroy_baton->post();
499 // We should schedule destroyInstances() only after the singleton was
500 // created. This will ensure it will be destroyed before singletons,
501 // not managed by folly::Singleton, which were initialized in its
503 scheduleDestroyInstances();
505 entry->instance = instance;
506 entry->instance_weak = instance;
507 entry->instance_ptr = instance.get();
508 entry->creating_thread = std::thread::id();
509 entry->destroy_baton = std::move(destroy_baton);
511 // This has to be the last step, because once state is Living other threads
512 // may access instance and instance_weak w/o synchronization.
513 entry->state.store(detail::SingletonEntryState::Living);
516 RWSpinLock::WriteHolder wh(&mutex_);
517 creation_order_.push_back(type);
522 typedef std::unique_ptr<detail::SingletonEntry> SingletonEntryPtr;
523 typedef std::unordered_map<detail::TypeDescriptor,
525 detail::TypeDescriptorHasher> SingletonMap;
527 /* Destroy and clean-up one singleton. Must be invoked while holding
528 * a read lock on mutex_.
529 * @param typeDescriptor - the type key for the removed singleton.
531 void destroyInstance(SingletonMap::iterator entry_it);
533 mutable folly::RWSpinLock mutex_;
534 SingletonMap singletons_;
535 std::vector<detail::TypeDescriptor> creation_order_;
536 SingletonVaultState state_{SingletonVaultState::Running};
537 bool registrationComplete_{false};
538 folly::RWSpinLock stateMutex_;
539 Type type_{Type::Relaxed};
542 // This is the wrapper class that most users actually interact with.
543 // It allows for simple access to registering and instantiating
544 // singletons. Create instances of this class in the global scope of
545 // type Singleton<T> to register your singleton for later access via
546 // Singleton<T>::get().
547 template <typename T,
548 typename Tag = detail::DefaultTag,
549 typename VaultTag = detail::DefaultTag /* for testing */>
552 typedef std::function<T*(void)> CreateFunc;
553 typedef std::function<void(T*)> TeardownFunc;
555 // Generally your program life cycle should be fine with calling
556 // get() repeatedly rather than saving the reference, and then not
557 // call get() during process shutdown.
559 return static_cast<T*>(
560 SingletonVault::singleton<VaultTag>()->get_ptr(typeDescriptor()));
563 // Same as get, but should be preffered to it in the same compilation
564 // unit, where Singleton is registered.
566 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
567 return reinterpret_cast<T*>(entry_->instance_ptr);
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 static std::weak_ptr<T> get_weak() {
579 (SingletonVault::singleton<VaultTag>())->get_weak(typeDescriptor());
581 // This is ugly and inefficient, but there's no other way to do it, because
582 // there's no static_pointer_cast for weak_ptr.
583 auto shared_void_ptr = weak_void_ptr.lock();
584 if (!shared_void_ptr) {
585 return std::weak_ptr<T>();
587 return std::static_pointer_cast<T>(shared_void_ptr);
590 // Same as get_weak, but should be preffered to it in the same compilation
591 // unit, where Singleton is registered.
592 std::weak_ptr<T> get_weak_fast() {
593 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
594 // This is ugly and inefficient, but there's no other way to do it,
595 // because there's no static_pointer_cast for weak_ptr.
596 auto shared_void_ptr = entry_->instance_weak.lock();
597 if (!shared_void_ptr) {
598 return std::weak_ptr<T>();
600 return std::static_pointer_cast<T>(shared_void_ptr);
606 // Allow the Singleton<t> instance to also retrieve the underlying
607 // singleton, if desired.
608 T* ptr() { return get_fast(); }
609 T& operator*() { return *ptr(); }
610 T* operator->() { return ptr(); }
612 explicit Singleton(std::nullptr_t _ = nullptr,
613 Singleton::TeardownFunc t = nullptr) :
614 Singleton ([]() { return new T; }, std::move(t)) {
617 explicit Singleton(Singleton::CreateFunc c,
618 Singleton::TeardownFunc t = nullptr) {
620 throw std::logic_error(
621 "nullptr_t should be passed if you want T to be default constructed");
624 auto vault = SingletonVault::singleton<VaultTag>();
627 &(vault->registerSingleton(typeDescriptor(), c, getTeardownFunc(t)));
631 * Construct and inject a mock singleton which should be used only from tests.
632 * Unlike regular singletons which are initialized once per process lifetime,
633 * mock singletons live for the duration of a test. This means that one process
634 * running multiple tests can initialize and register the same singleton
635 * multiple times. This functionality should be used only from tests
636 * since it relaxes validation and performance in order to be able to perform
637 * the injection. The returned mock singleton is functionality identical to
638 * regular singletons.
640 static void make_mock(std::nullptr_t c = nullptr,
641 typename Singleton<T>::TeardownFunc t = nullptr) {
642 make_mock([]() { return new T; }, t);
645 static void make_mock(CreateFunc c,
646 typename Singleton<T>::TeardownFunc t = nullptr) {
648 throw std::logic_error(
649 "nullptr_t should be passed if you want T to be default constructed");
652 auto vault = SingletonVault::singleton<VaultTag>();
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_;