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/Exception.h>
96 #include <folly/Hash.h>
97 #include <folly/Memory.h>
98 #include <folly/RWSpinLock.h>
99 #include <folly/io/async/Request.h>
105 #include <condition_variable>
107 #include <unordered_map>
108 #include <functional>
112 #include <glog/logging.h>
116 // For actual usage, please see the Singleton<T> class at the bottom
117 // of this file; that is what you will actually interact with.
119 // SingletonVault is the class that manages singleton instances. It
120 // is unaware of the underlying types of singletons, and simply
121 // manages lifecycles and invokes CreateFunc and TeardownFunc when
122 // appropriate. In general, you won't need to interact with the
123 // SingletonVault itself.
125 // A vault goes through a few stages of life:
127 // 1. Registration phase; singletons can be registered, but no
128 // singleton can be created.
129 // 2. registrationComplete() has been called; singletons can no
130 // longer be registered, but they can be created.
131 // 3. A vault can return to stage 1 when destroyInstances is called.
133 // In general, you don't need to worry about any of the above; just
134 // ensure registrationComplete() is called near the top of your main()
135 // function, otherwise no singletons can be instantiated.
139 struct DefaultTag {};
141 // A TypeDescriptor is the unique handle for a given singleton. It is
142 // a combinaiton of the type and of the optional name, and is used as
143 // a key in unordered_maps.
144 class TypeDescriptor {
146 TypeDescriptor(const std::type_info& ti,
147 const std::type_info& tag_ti)
148 : ti_(ti), tag_ti_(tag_ti) {
151 TypeDescriptor(const TypeDescriptor& other)
152 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
155 TypeDescriptor& operator=(const TypeDescriptor& other) {
156 if (this != &other) {
158 tag_ti_ = other.tag_ti_;
164 std::string name() const {
165 std::string ret = ti_.name();
166 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
168 ret += tag_ti_.name();
173 friend class TypeDescriptorHasher;
175 bool operator==(const TypeDescriptor& other) const {
176 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
181 std::type_index tag_ti_;
184 class TypeDescriptorHasher {
186 size_t operator()(const TypeDescriptor& ti) const {
187 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
191 enum class SingletonEntryState {
196 // An actual instance of a singleton, tracking the instance itself,
197 // its state as described above, and the create and teardown
199 struct SingletonEntry {
200 typedef std::function<void(void*)> TeardownFunc;
201 typedef std::function<void*(void)> CreateFunc;
203 SingletonEntry(CreateFunc c, TeardownFunc t) :
204 create(std::move(c)), teardown(std::move(t)) {}
206 // mutex protects the entire entry during construction/destruction
209 // State of the singleton entry. If state is Living, instance_ptr and
210 // instance_weak can be safely accessed w/o synchronization.
211 std::atomic<SingletonEntryState> state{SingletonEntryState::Dead};
213 // the thread creating the singleton (only valid while creating an object)
214 std::thread::id creating_thread;
216 // The singleton itself and related functions.
218 // holds a shared_ptr to singleton instance, set when state is changed from
219 // Dead to Living. Reset when state is changed from Living to Dead.
220 std::shared_ptr<void> instance;
221 // weak_ptr to the singleton instance, set when state is changed from Dead
222 // to Living. We never write to this object after initialization, so it is
223 // safe to read it from different threads w/o synchronization if we know
224 // that state is set to Living
225 std::weak_ptr<void> instance_weak;
226 void* instance_ptr = nullptr;
227 CreateFunc create = nullptr;
228 TeardownFunc teardown = nullptr;
230 SingletonEntry(const SingletonEntry&) = delete;
231 SingletonEntry& operator=(const SingletonEntry&) = delete;
232 SingletonEntry& operator=(SingletonEntry&&) = delete;
233 SingletonEntry(SingletonEntry&&) = delete;
238 class SingletonVault {
240 enum class Type { Strict, Relaxed };
242 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
244 // Destructor is only called by unit tests to check destroyInstances.
247 typedef std::function<void(void*)> TeardownFunc;
248 typedef std::function<void*(void)> CreateFunc;
250 // Ensure that Singleton has not been registered previously and that
251 // registration is not complete. If validations succeeds,
252 // register a singleton of a given type with the create and teardown
254 detail::SingletonEntry& registerSingleton(detail::TypeDescriptor type,
256 TeardownFunc teardown) {
257 RWSpinLock::ReadHolder rh(&stateMutex_);
259 stateCheck(SingletonVaultState::Running);
261 if (UNLIKELY(registrationComplete_)) {
262 throw std::logic_error(
263 "Registering singleton after registrationComplete().");
266 RWSpinLock::ReadHolder rhMutex(&mutex_);
267 CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
269 return registerSingletonImpl(type, create, teardown);
272 // Register a singleton of a given type with the create and teardown
273 // functions. Must hold reader locks on stateMutex_ and mutex_
274 // when invoking this function.
275 detail::SingletonEntry& registerSingletonImpl(detail::TypeDescriptor type,
277 TeardownFunc teardown) {
278 RWSpinLock::UpgradedHolder wh(&mutex_);
281 folly::make_unique<detail::SingletonEntry>(std::move(create),
282 std::move(teardown));
283 return *singletons_[type];
286 /* Register a mock singleton used for testing of singletons which
287 * depend on other private singletons which cannot be otherwise injected.
289 void registerMockSingleton(detail::TypeDescriptor type,
291 TeardownFunc teardown) {
292 RWSpinLock::ReadHolder rh(&stateMutex_);
293 RWSpinLock::ReadHolder rhMutex(&mutex_);
295 auto entry_it = singletons_.find(type);
296 // Mock singleton registration, we allow existing entry to be overridden.
297 if (entry_it == singletons_.end()) {
298 throw std::logic_error(
299 "Registering mock before the singleton was registered");
303 auto& entry = *(entry_it->second);
304 // Destroy existing singleton.
305 std::lock_guard<std::mutex> entry_lg(entry.mutex);
307 destroyInstance(entry_it);
308 entry.create = create;
309 entry.teardown = teardown;
312 // Upgrade to write lock.
313 RWSpinLock::UpgradedHolder whMutex(&mutex_);
315 // Remove singleton from creation order and singletons_.
316 // This happens only in test code and not frequently.
317 // Performance is not a concern here.
318 auto creation_order_it = std::find(
319 creation_order_.begin(),
320 creation_order_.end(),
322 if (creation_order_it != creation_order_.end()) {
323 creation_order_.erase(creation_order_it);
327 // Mark registration is complete; no more singletons can be
328 // registered at this point.
329 void registrationComplete() {
330 RequestContext::getStaticContext();
331 std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
333 RWSpinLock::WriteHolder wh(&stateMutex_);
335 stateCheck(SingletonVaultState::Running);
337 if (type_ == Type::Strict) {
338 for (const auto& id_singleton_entry: singletons_) {
339 const auto& singleton_entry = *id_singleton_entry.second;
340 if (singleton_entry.state != detail::SingletonEntryState::Dead) {
341 throw std::runtime_error(
342 "Singleton created before registration was complete.");
347 registrationComplete_ = true;
350 // Destroy all singletons; when complete, the vault can't create
351 // singletons once again until reenableInstances() is called.
352 void destroyInstances();
354 // Enable re-creating singletons after destroyInstances() was called.
355 void reenableInstances();
357 // Retrieve a singleton from the vault, creating it if necessary.
358 std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
359 auto entry = get_entry_create(type);
360 return entry->instance_weak;
363 // This function is inherently racy since we don't hold the
364 // shared_ptr that contains the Singleton. It is the caller's
365 // responsibility to be sane with this, but it is preferable to use
366 // the weak_ptr interface for true safety.
367 void* get_ptr(detail::TypeDescriptor type) {
368 auto entry = get_entry_create(type);
369 if (UNLIKELY(entry->instance_weak.expired())) {
370 throw std::runtime_error(
371 "Raw pointer to a singleton requested after its destruction.");
373 return entry->instance_ptr;
376 // For testing; how many registered and living singletons we have.
377 size_t registeredSingletonCount() const {
378 RWSpinLock::ReadHolder rh(&mutex_);
380 return singletons_.size();
383 size_t livingSingletonCount() const {
384 RWSpinLock::ReadHolder rh(&mutex_);
387 for (const auto& p : singletons_) {
388 if (p.second->state == detail::SingletonEntryState::Living) {
396 // A well-known vault; you can actually have others, but this is the
398 static SingletonVault* singleton();
401 // The two stages of life for a vault, as mentioned in the class comment.
402 enum class SingletonVaultState {
407 // Each singleton in the vault can be in two states: dead
408 // (registered but never created), living (CreateFunc returned an instance).
410 void stateCheck(SingletonVaultState expected,
411 const char* msg="Unexpected singleton state change") {
412 if (expected != state_) {
413 throw std::logic_error(msg);
417 // This method only matters if registrationComplete() is never called.
418 // Otherwise destroyInstances is scheduled to be executed atexit.
420 // Initializes static object, which calls destroyInstances on destruction.
421 // Used to have better deletion ordering with singleton not managed by
422 // folly::Singleton. The desruction will happen in the following order:
423 // 1. Singletons, not managed by folly::Singleton, which were created after
424 // any of the singletons managed by folly::Singleton was requested.
425 // 2. All singletons managed by folly::Singleton
426 // 3. Singletons, not managed by folly::Singleton, which were created before
427 // any of the singletons managed by folly::Singleton was requested.
428 static void scheduleDestroyInstances();
430 detail::SingletonEntry* get_entry(detail::TypeDescriptor type) {
431 RWSpinLock::ReadHolder rh(&mutex_);
433 auto it = singletons_.find(type);
434 if (it == singletons_.end()) {
435 throw std::out_of_range(std::string("non-existent singleton: ") +
439 return it->second.get();
442 // Get a pointer to the living SingletonEntry for the specified
443 // type. The singleton is created as part of this function, if
445 detail::SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
446 auto entry = get_entry(type);
448 if (LIKELY(entry->state == detail::SingletonEntryState::Living)) {
452 // There's no synchronization here, so we may not see the current value
453 // for creating_thread if it was set by other thread, but we only care about
454 // it if it was set by current thread anyways.
455 if (entry->creating_thread == std::this_thread::get_id()) {
456 throw std::out_of_range(std::string("circular singleton dependency: ") +
460 std::lock_guard<std::mutex> entry_lock(entry->mutex);
462 if (entry->state == detail::SingletonEntryState::Living) {
466 entry->creating_thread = std::this_thread::get_id();
468 RWSpinLock::ReadHolder rh(&stateMutex_);
469 if (state_ == SingletonVaultState::Quiescing) {
470 entry->creating_thread = std::thread::id();
474 // Can't use make_shared -- no support for a custom deleter, sadly.
475 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
477 // We should schedule destroyInstances() only after the singleton was
478 // created. This will ensure it will be destroyed before singletons,
479 // not managed by folly::Singleton, which were initialized in its
481 scheduleDestroyInstances();
483 entry->instance = instance;
484 entry->instance_weak = instance;
485 entry->instance_ptr = instance.get();
486 entry->creating_thread = std::thread::id();
488 // This has to be the last step, because once state is Living other threads
489 // may access instance and instance_weak w/o synchronization.
490 entry->state.store(detail::SingletonEntryState::Living);
493 RWSpinLock::WriteHolder wh(&mutex_);
494 creation_order_.push_back(type);
499 typedef std::unique_ptr<detail::SingletonEntry> SingletonEntryPtr;
500 typedef std::unordered_map<detail::TypeDescriptor,
502 detail::TypeDescriptorHasher> SingletonMap;
504 /* Destroy and clean-up one singleton. Must be invoked while holding
505 * a read lock on mutex_.
506 * @param typeDescriptor - the type key for the removed singleton.
508 void destroyInstance(SingletonMap::iterator entry_it);
510 mutable folly::RWSpinLock mutex_;
511 SingletonMap singletons_;
512 std::vector<detail::TypeDescriptor> creation_order_;
513 SingletonVaultState state_{SingletonVaultState::Running};
514 bool registrationComplete_{false};
515 folly::RWSpinLock stateMutex_;
516 Type type_{Type::Relaxed};
519 // This is the wrapper class that most users actually interact with.
520 // It allows for simple access to registering and instantiating
521 // singletons. Create instances of this class in the global scope of
522 // type Singleton<T> to register your singleton for later access via
523 // Singleton<T>::get().
524 template <typename T, typename Tag = detail::DefaultTag>
527 typedef std::function<T*(void)> CreateFunc;
528 typedef std::function<void(T*)> TeardownFunc;
530 // Generally your program life cycle should be fine with calling
531 // get() repeatedly rather than saving the reference, and then not
532 // call get() during process shutdown.
533 static T* get(SingletonVault* vault = nullptr /* for testing */) {
534 return static_cast<T*>(
535 (vault ?: SingletonVault::singleton())->get_ptr(typeDescriptor()));
538 // Same as get, but should be preffered to it in the same compilation
539 // unit, where Singleton is registered.
541 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
542 return reinterpret_cast<T*>(entry_->instance_ptr);
548 // If, however, you do need to hold a reference to the specific
549 // singleton, you can try to do so with a weak_ptr. Avoid this when
550 // possible but the inability to lock the weak pointer can be a
551 // signal that the vault has been destroyed.
552 static std::weak_ptr<T> get_weak(
553 SingletonVault* vault = nullptr /* for testing */) {
555 (vault ?: SingletonVault::singleton())->get_weak(typeDescriptor());
557 // This is ugly and inefficient, but there's no other way to do it, because
558 // there's no static_pointer_cast for weak_ptr.
559 auto shared_void_ptr = weak_void_ptr.lock();
560 if (!shared_void_ptr) {
561 return std::weak_ptr<T>();
563 return std::static_pointer_cast<T>(shared_void_ptr);
566 // Same as get_weak, but should be preffered to it in the same compilation
567 // unit, where Singleton is registered.
568 std::weak_ptr<T> get_weak_fast() {
569 if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
570 // This is ugly and inefficient, but there's no other way to do it,
571 // because there's no static_pointer_cast for weak_ptr.
572 auto shared_void_ptr = entry_->instance_weak.lock();
573 if (!shared_void_ptr) {
574 return std::weak_ptr<T>();
576 return std::static_pointer_cast<T>(shared_void_ptr);
578 return get_weak(vault_);
582 // Allow the Singleton<t> instance to also retrieve the underlying
583 // singleton, if desired.
584 T* ptr() { return get_fast(); }
585 T& operator*() { return *ptr(); }
586 T* operator->() { return ptr(); }
588 explicit Singleton(std::nullptr_t _ = nullptr,
589 Singleton::TeardownFunc t = nullptr,
590 SingletonVault* vault = nullptr) :
591 Singleton ([]() { return new T; },
596 explicit Singleton(Singleton::CreateFunc c,
597 Singleton::TeardownFunc t = nullptr,
598 SingletonVault* vault = nullptr) {
600 throw std::logic_error(
601 "nullptr_t should be passed if you want T to be default constructed");
604 if (vault == nullptr) {
605 vault = SingletonVault::singleton();
610 &(vault->registerSingleton(typeDescriptor(), c, getTeardownFunc(t)));
614 * Construct and inject a mock singleton which should be used only from tests.
615 * Unlike regular singletons which are initialized once per process lifetime,
616 * mock singletons live for the duration of a test. This means that one process
617 * running multiple tests can initialize and register the same singleton
618 * multiple times. This functionality should be used only from tests
619 * since it relaxes validation and performance in order to be able to perform
620 * the injection. The returned mock singleton is functionality identical to
621 * regular singletons.
623 static void make_mock(std::nullptr_t c = nullptr,
624 typename Singleton<T>::TeardownFunc t = nullptr,
625 SingletonVault* vault = nullptr /* for testing */ ) {
626 make_mock([]() { return new T; }, t, vault);
629 static void make_mock(CreateFunc c,
630 typename Singleton<T>::TeardownFunc t = nullptr,
631 SingletonVault* vault = nullptr /* for testing */ ) {
633 throw std::logic_error(
634 "nullptr_t should be passed if you want T to be default constructed");
637 if (vault == nullptr) {
638 vault = SingletonVault::singleton();
641 vault->registerMockSingleton(
648 static detail::TypeDescriptor typeDescriptor() {
649 return {typeid(T), typeid(Tag)};
652 // Construct SingletonVault::TeardownFunc.
653 static SingletonVault::TeardownFunc getTeardownFunc(
655 SingletonVault::TeardownFunc teardown;
657 teardown = [](void* v) { delete static_cast<T*>(v); };
659 teardown = [t](void* v) { t(static_cast<T*>(v)); };
665 // This is pointing to SingletonEntry paired with this singleton object. This
666 // is never reset, so each SingletonEntry should never be destroyed.
667 // We rely on the fact that Singleton destructor won't reset this pointer, so
668 // it can be "safely" used even after static Singleton object is destroyed.
669 detail::SingletonEntry* entry_;
670 SingletonVault* vault_;