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 // 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 name:
54 // folly::Singleton<MyExpensiveService> s1("name1");
55 // folly::Singleton<MyExpensiveService> s2("name2");
58 // MyExpensiveService* svc1 = Singleton<MyExpensiveService>::get("name1");
59 // MyExpensiveService* svc2 = Singleton<MyExpensiveService>::get("name2");
61 // By default, the singleton instance is constructed via new and
62 // deleted via delete, but this is configurable:
64 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
67 // Where create and destroy are functions, Singleton<T>::CreateFunc
68 // Singleton<T>::TeardownFunc.
70 // What if you need to destroy all of your singletons? Say, some of
71 // your singletons manage threads, but you need to fork? Or your unit
72 // test wants to clean up all global state? Then you can call
73 // SingletonVault::singleton()->destroyInstances(), which invokes the
74 // TeardownFunc for each singleton, in the reverse order they were
75 // created. It is your responsibility to ensure your singletons can
76 // handle cases where the singletons they depend on go away, however.
77 // Singletons won't be recreated after destroyInstances call. If you
78 // want to re-enable singleton creation (say after fork was called) you
79 // should call reenableInstances.
82 #include <folly/Exception.h>
83 #include <folly/Hash.h>
84 #include <folly/RWSpinLock.h>
89 #include <condition_variable>
91 #include <unordered_map>
96 #include <glog/logging.h>
100 // For actual usage, please see the Singleton<T> class at the bottom
101 // of this file; that is what you will actually interact with.
103 // SingletonVault is the class that manages singleton instances. It
104 // is unaware of the underlying types of singletons, and simply
105 // manages lifecycles and invokes CreateFunc and TeardownFunc when
106 // appropriate. In general, you won't need to interact with the
107 // SingletonVault itself.
109 // A vault goes through a few stages of life:
111 // 1. Registration phase; singletons can be registered, but no
112 // singleton can be created.
113 // 2. registrationComplete() has been called; singletons can no
114 // longer be registered, but they can be created.
115 // 3. A vault can return to stage 1 when destroyInstances is called.
117 // In general, you don't need to worry about any of the above; just
118 // ensure registrationComplete() is called near the top of your main()
119 // function, otherwise no singletons can be instantiated.
123 const char* const kDefaultTypeDescriptorName = "(default)";
124 // A TypeDescriptor is the unique handle for a given singleton. It is
125 // a combinaiton of the type and of the optional name, and is used as
126 // a key in unordered_maps.
127 class TypeDescriptor {
129 TypeDescriptor(const std::type_info& ti, std::string name)
130 : ti_(ti), name_(name) {
131 if (name_ == kDefaultTypeDescriptorName) {
132 LOG(DFATAL) << "Caller used the default name as their literal name; "
133 << "name your singleton something other than "
134 << kDefaultTypeDescriptorName;
138 std::string name() const {
139 std::string ret = ti_.name();
142 ret += kDefaultTypeDescriptorName;
149 friend class TypeDescriptorHasher;
151 bool operator==(const TypeDescriptor& other) const {
152 return ti_ == other.ti_ && name_ == other.name_;
156 const std::type_index ti_;
157 const std::string name_;
160 class TypeDescriptorHasher {
162 size_t operator()(const TypeDescriptor& ti) const {
163 return folly::hash::hash_combine(ti.ti_, ti.name_);
168 class SingletonVault {
170 enum class Type { Strict, Relaxed };
172 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
174 // Destructor is only called by unit tests to check destroyInstances.
177 typedef std::function<void(void*)> TeardownFunc;
178 typedef std::function<void*(void)> CreateFunc;
180 // Register a singleton of a given type with the create and teardown
182 void registerSingleton(detail::TypeDescriptor type,
184 TeardownFunc teardown) {
185 RWSpinLock::ReadHolder rh(&stateMutex_);
187 stateCheck(SingletonVaultState::Running);
188 if (UNLIKELY(registrationComplete_)) {
189 throw std::logic_error(
190 "Registering singleton after registrationComplete().");
193 RWSpinLock::WriteHolder wh(&mutex_);
195 CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
196 auto& entry = singletons_[type];
197 entry.reset(new SingletonEntry);
199 std::lock_guard<std::mutex> entry_guard(entry->mutex);
200 CHECK(entry->instance == nullptr);
203 entry->create = create;
204 entry->teardown = teardown;
205 entry->state = SingletonEntryState::Dead;
208 // Mark registration is complete; no more singletons can be
209 // registered at this point.
210 void registrationComplete() {
211 RWSpinLock::WriteHolder wh(&stateMutex_);
213 stateCheck(SingletonVaultState::Running);
215 if (type_ == Type::Strict) {
216 for (const auto& id_singleton_entry: singletons_) {
217 const auto& singleton_entry = *id_singleton_entry.second;
218 if (singleton_entry.state != SingletonEntryState::Dead) {
219 throw std::runtime_error(
220 "Singleton created before registration was complete.");
225 registrationComplete_ = true;
228 // Destroy all singletons; when complete, the vault can't create
229 // singletons once again until reenableInstances() is called.
230 void destroyInstances();
232 // Enable re-creating singletons after destroyInstances() was called.
233 void reenableInstances();
235 // Retrieve a singleton from the vault, creating it if necessary.
236 std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
237 auto entry = get_entry_create(type);
238 return entry->instance_weak;
241 // This function is inherently racy since we don't hold the
242 // shared_ptr that contains the Singleton. It is the caller's
243 // responsibility to be sane with this, but it is preferable to use
244 // the weak_ptr interface for true safety.
245 void* get_ptr(detail::TypeDescriptor type) {
246 auto entry = get_entry_create(type);
247 if (UNLIKELY(entry->instance_weak.expired())) {
248 throw std::runtime_error(
249 "Raw pointer to a singleton requested after its destruction.");
251 return entry->instance_ptr;
254 // For testing; how many registered and living singletons we have.
255 size_t registeredSingletonCount() const {
256 RWSpinLock::ReadHolder rh(&mutex_);
258 return singletons_.size();
261 size_t livingSingletonCount() const {
262 RWSpinLock::ReadHolder rh(&mutex_);
265 for (const auto& p : singletons_) {
266 std::lock_guard<std::mutex> entry_guard(p.second->mutex);
267 if (p.second->instance) {
275 // A well-known vault; you can actually have others, but this is the
277 static SingletonVault* singleton();
280 // The two stages of life for a vault, as mentioned in the class comment.
281 enum class SingletonVaultState {
286 // Each singleton in the vault can be in three states: dead
287 // (registered but never created), being born (running the
288 // CreateFunc), and living (CreateFunc returned an instance).
289 enum class SingletonEntryState {
295 void stateCheck(SingletonVaultState expected,
296 const char* msg="Unexpected singleton state change") {
297 if (expected != state_) {
298 throw std::logic_error(msg);
302 // An actual instance of a singleton, tracking the instance itself,
303 // its state as described above, and the create and teardown
305 struct SingletonEntry {
306 // mutex protects the entire entry
309 // state changes notify state_condvar
310 SingletonEntryState state = SingletonEntryState::Dead;
311 std::condition_variable state_condvar;
313 // the thread creating the singleton
314 std::thread::id creating_thread;
316 // The singleton itself and related functions.
317 std::shared_ptr<void> instance;
318 std::weak_ptr<void> instance_weak;
319 void* instance_ptr = nullptr;
320 CreateFunc create = nullptr;
321 TeardownFunc teardown = nullptr;
323 SingletonEntry() = default;
324 SingletonEntry(const SingletonEntry&) = delete;
325 SingletonEntry& operator=(const SingletonEntry&) = delete;
326 SingletonEntry& operator=(SingletonEntry&&) = delete;
327 SingletonEntry(SingletonEntry&&) = delete;
330 // Initializes static object, which calls destroyInstances on destruction.
331 // Used to have better deletion ordering with singleton not managed by
332 // folly::Singleton. The desruction will happen in the following order:
333 // 1. Singletons, not managed by folly::Singleton, which were created after
334 // any of the singletons managed by folly::Singleton was requested.
335 // 2. All singletons managed by folly::Singleton
336 // 3. Singletons, not managed by folly::Singleton, which were created before
337 // any of the singletons managed by folly::Singleton was requested.
338 static void scheduleDestroyInstances();
340 SingletonEntry* get_entry(detail::TypeDescriptor type) {
341 RWSpinLock::ReadHolder rh(&mutex_);
343 auto it = singletons_.find(type);
344 if (it == singletons_.end()) {
345 throw std::out_of_range(std::string("non-existent singleton: ") +
349 return it->second.get();
352 // Get a pointer to the living SingletonEntry for the specified
353 // type. The singleton is created as part of this function, if
355 SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
356 auto entry = get_entry(type);
358 std::unique_lock<std::mutex> entry_lock(entry->mutex);
360 if (entry->state == SingletonEntryState::BeingBorn) {
361 // If this thread is trying to give birth to the singleton, it's
362 // a circular dependency and we must panic.
363 if (entry->creating_thread == std::this_thread::get_id()) {
364 throw std::out_of_range(std::string("circular singleton dependency: ") +
368 entry->state_condvar.wait(entry_lock, [&entry]() {
369 return entry->state != SingletonEntryState::BeingBorn;
373 if (entry->instance == nullptr) {
374 RWSpinLock::ReadHolder rh(&stateMutex_);
375 if (state_ == SingletonVaultState::Quiescing) {
379 CHECK(entry->state == SingletonEntryState::Dead);
380 entry->state = SingletonEntryState::BeingBorn;
381 entry->creating_thread = std::this_thread::get_id();
384 // Can't use make_shared -- no support for a custom deleter, sadly.
385 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
387 // We should schedule destroyInstances() only after the singleton was
388 // created. This will ensure it will be destroyed before singletons,
389 // not managed by folly::Singleton, which were initialized in its
391 scheduleDestroyInstances();
395 CHECK(entry->state == SingletonEntryState::BeingBorn);
396 entry->instance = instance;
397 entry->instance_weak = instance;
398 entry->instance_ptr = instance.get();
399 entry->state = SingletonEntryState::Living;
400 entry->state_condvar.notify_all();
403 RWSpinLock::WriteHolder wh(&mutex_);
405 creation_order_.push_back(type);
408 CHECK(entry->state == SingletonEntryState::Living);
412 mutable folly::RWSpinLock mutex_;
413 typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
414 std::unordered_map<detail::TypeDescriptor,
416 detail::TypeDescriptorHasher> singletons_;
417 std::vector<detail::TypeDescriptor> creation_order_;
418 SingletonVaultState state_{SingletonVaultState::Running};
419 bool registrationComplete_{false};
420 folly::RWSpinLock stateMutex_;
421 Type type_{Type::Relaxed};
424 // This is the wrapper class that most users actually interact with.
425 // It allows for simple access to registering and instantiating
426 // singletons. Create instances of this class in the global scope of
427 // type Singleton<T> to register your singleton for later access via
428 // Singleton<T>::get().
429 template <typename T>
432 typedef std::function<T*(void)> CreateFunc;
433 typedef std::function<void(T*)> TeardownFunc;
435 // Generally your program life cycle should be fine with calling
436 // get() repeatedly rather than saving the reference, and then not
437 // call get() during process shutdown.
438 static T* get(SingletonVault* vault = nullptr /* for testing */) {
439 return get_ptr({typeid(T), ""}, vault);
442 static T* get(const char* name,
443 SingletonVault* vault = nullptr /* for testing */) {
444 return get_ptr({typeid(T), name}, vault);
447 // If, however, you do need to hold a reference to the specific
448 // singleton, you can try to do so with a weak_ptr. Avoid this when
449 // possible but the inability to lock the weak pointer can be a
450 // signal that the vault has been destroyed.
451 static std::weak_ptr<T> get_weak(
452 SingletonVault* vault = nullptr /* for testing */) {
453 return get_weak("", vault);
456 static std::weak_ptr<T> get_weak(
457 const char* name, SingletonVault* vault = nullptr /* for testing */) {
459 (vault ?: SingletonVault::singleton())->get_weak({typeid(T), name});
461 // This is ugly and inefficient, but there's no other way to do it, because
462 // there's no static_pointer_cast for weak_ptr.
463 auto shared_void_ptr = weak_void_ptr.lock();
464 if (!shared_void_ptr) {
465 return std::weak_ptr<T>();
467 return std::static_pointer_cast<T>(shared_void_ptr);
470 // Allow the Singleton<t> instance to also retrieve the underlying
471 // singleton, if desired.
472 T* ptr() { return get_ptr(type_descriptor_, vault_); }
473 T& operator*() { return *ptr(); }
474 T* operator->() { return ptr(); }
476 template <typename CreateFunc = std::nullptr_t>
477 explicit Singleton(CreateFunc c = nullptr,
478 Singleton::TeardownFunc t = nullptr,
479 SingletonVault* vault = nullptr /* for testing */)
480 : Singleton({typeid(T), ""}, c, t, vault) {}
482 template <typename CreateFunc = std::nullptr_t>
483 explicit Singleton(const char* name,
484 CreateFunc c = nullptr,
485 Singleton::TeardownFunc t = nullptr,
486 SingletonVault* vault = nullptr /* for testing */)
487 : Singleton({typeid(T), name}, c, t, vault) {}
490 explicit Singleton(detail::TypeDescriptor type,
492 Singleton::TeardownFunc t,
493 SingletonVault* vault) :
495 []() { return new T; },
500 explicit Singleton(detail::TypeDescriptor type,
501 Singleton::CreateFunc c,
502 Singleton::TeardownFunc t,
503 SingletonVault* vault)
504 : type_descriptor_(type) {
506 throw std::logic_error(
507 "nullptr_t should be passed if you want T to be default constructed");
509 SingletonVault::TeardownFunc teardown;
511 teardown = [](void* v) { delete static_cast<T*>(v); };
513 teardown = [t](void* v) { t(static_cast<T*>(v)); };
516 if (vault == nullptr) {
517 vault = SingletonVault::singleton();
520 vault->registerSingleton(type, c, teardown);
523 static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
524 SingletonVault* vault = nullptr /* for testing */) {
525 return static_cast<T*>(
526 (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
529 // Don't use this function, it's private for a reason! Using it
530 // would defeat the *entire purpose* of the vault in that we lose
531 // the ability to guarantee that, after a destroyInstances is
532 // called, all instances are, in fact, destroyed. You should use
533 // weak_ptr if you need to hold a reference to the singleton and
534 // guarantee briefly that it exists.
536 // Yes, you can just get the weak pointer and lock it, but hopefully
537 // if you have taken the time to read this far, you see why that
539 static std::shared_ptr<T> get_shared(
540 detail::TypeDescriptor type_descriptor = {typeid(T), ""},
541 SingletonVault* vault = nullptr /* for testing */) {
542 return std::static_pointer_cast<T>(
543 (vault ?: SingletonVault::singleton())->get_weak(type_descriptor).lock());
546 detail::TypeDescriptor type_descriptor_;
547 SingletonVault* vault_;