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 scheduleDestroyInstances();
213 RWSpinLock::WriteHolder wh(&stateMutex_);
215 stateCheck(SingletonVaultState::Running);
217 if (type_ == Type::Strict) {
218 for (const auto& id_singleton_entry: singletons_) {
219 const auto& singleton_entry = *id_singleton_entry.second;
220 if (singleton_entry.state != SingletonEntryState::Dead) {
221 throw std::runtime_error(
222 "Singleton created before registration was complete.");
227 registrationComplete_ = true;
230 // Destroy all singletons; when complete, the vault can't create
231 // singletons once again until reenableInstances() is called.
232 void destroyInstances();
234 // Enable re-creating singletons after destroyInstances() was called.
235 void reenableInstances();
237 // Retrieve a singleton from the vault, creating it if necessary.
238 std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
239 auto entry = get_entry_create(type);
240 return entry->instance_weak;
243 // This function is inherently racy since we don't hold the
244 // shared_ptr that contains the Singleton. It is the caller's
245 // responsibility to be sane with this, but it is preferable to use
246 // the weak_ptr interface for true safety.
247 void* get_ptr(detail::TypeDescriptor type) {
248 auto entry = get_entry_create(type);
249 if (UNLIKELY(entry->instance_weak.expired())) {
250 throw std::runtime_error(
251 "Raw pointer to a singleton requested after its destruction.");
253 return entry->instance_ptr;
256 // For testing; how many registered and living singletons we have.
257 size_t registeredSingletonCount() const {
258 RWSpinLock::ReadHolder rh(&mutex_);
260 return singletons_.size();
263 size_t livingSingletonCount() const {
264 RWSpinLock::ReadHolder rh(&mutex_);
267 for (const auto& p : singletons_) {
268 std::lock_guard<std::mutex> entry_guard(p.second->mutex);
269 if (p.second->instance) {
277 // A well-known vault; you can actually have others, but this is the
279 static SingletonVault* singleton();
282 // The two stages of life for a vault, as mentioned in the class comment.
283 enum class SingletonVaultState {
288 // Each singleton in the vault can be in three states: dead
289 // (registered but never created), being born (running the
290 // CreateFunc), and living (CreateFunc returned an instance).
291 enum class SingletonEntryState {
297 void stateCheck(SingletonVaultState expected,
298 const char* msg="Unexpected singleton state change") {
299 if (expected != state_) {
300 throw std::logic_error(msg);
304 // An actual instance of a singleton, tracking the instance itself,
305 // its state as described above, and the create and teardown
307 struct SingletonEntry {
308 // mutex protects the entire entry
311 // state changes notify state_condvar
312 SingletonEntryState state = SingletonEntryState::Dead;
313 std::condition_variable state_condvar;
315 // the thread creating the singleton
316 std::thread::id creating_thread;
318 // The singleton itself and related functions.
319 std::shared_ptr<void> instance;
320 std::weak_ptr<void> instance_weak;
321 void* instance_ptr = nullptr;
322 CreateFunc create = nullptr;
323 TeardownFunc teardown = nullptr;
325 SingletonEntry() = default;
326 SingletonEntry(const SingletonEntry&) = delete;
327 SingletonEntry& operator=(const SingletonEntry&) = delete;
328 SingletonEntry& operator=(SingletonEntry&&) = delete;
329 SingletonEntry(SingletonEntry&&) = delete;
332 // Initializes static object, which calls destroyInstances on destruction.
333 // Used to have better deletion ordering with singleton not managed by
334 // folly::Singleton. The desruction will happen in the following order:
335 // 1. Singletons, not managed by folly::Singleton, which were created after
336 // any of the singletons managed by folly::Singleton was requested.
337 // 2. All singletons managed by folly::Singleton
338 // 3. Singletons, not managed by folly::Singleton, which were created before
339 // any of the singletons managed by folly::Singleton was requested.
340 static void scheduleDestroyInstances();
342 SingletonEntry* get_entry(detail::TypeDescriptor type) {
343 RWSpinLock::ReadHolder rh(&mutex_);
345 auto it = singletons_.find(type);
346 if (it == singletons_.end()) {
347 throw std::out_of_range(std::string("non-existent singleton: ") +
351 return it->second.get();
354 // Get a pointer to the living SingletonEntry for the specified
355 // type. The singleton is created as part of this function, if
357 SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
358 auto entry = get_entry(type);
360 std::unique_lock<std::mutex> entry_lock(entry->mutex);
362 if (entry->state == SingletonEntryState::BeingBorn) {
363 // If this thread is trying to give birth to the singleton, it's
364 // a circular dependency and we must panic.
365 if (entry->creating_thread == std::this_thread::get_id()) {
366 throw std::out_of_range(std::string("circular singleton dependency: ") +
370 entry->state_condvar.wait(entry_lock, [&entry]() {
371 return entry->state != SingletonEntryState::BeingBorn;
375 if (entry->instance == nullptr) {
376 RWSpinLock::ReadHolder rh(&stateMutex_);
377 if (state_ == SingletonVaultState::Quiescing) {
381 CHECK(entry->state == SingletonEntryState::Dead);
382 entry->state = SingletonEntryState::BeingBorn;
383 entry->creating_thread = std::this_thread::get_id();
386 // Can't use make_shared -- no support for a custom deleter, sadly.
387 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
389 // We should schedule destroyInstances() only after the singleton was
390 // created. This will ensure it will be destroyed before singletons,
391 // not managed by folly::Singleton, which were initialized in its
393 scheduleDestroyInstances();
397 CHECK(entry->state == SingletonEntryState::BeingBorn);
398 entry->instance = instance;
399 entry->instance_weak = instance;
400 entry->instance_ptr = instance.get();
401 entry->state = SingletonEntryState::Living;
402 entry->state_condvar.notify_all();
405 RWSpinLock::WriteHolder wh(&mutex_);
407 creation_order_.push_back(type);
410 CHECK(entry->state == SingletonEntryState::Living);
414 mutable folly::RWSpinLock mutex_;
415 typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
416 std::unordered_map<detail::TypeDescriptor,
418 detail::TypeDescriptorHasher> singletons_;
419 std::vector<detail::TypeDescriptor> creation_order_;
420 SingletonVaultState state_{SingletonVaultState::Running};
421 bool registrationComplete_{false};
422 folly::RWSpinLock stateMutex_;
423 Type type_{Type::Relaxed};
426 // This is the wrapper class that most users actually interact with.
427 // It allows for simple access to registering and instantiating
428 // singletons. Create instances of this class in the global scope of
429 // type Singleton<T> to register your singleton for later access via
430 // Singleton<T>::get().
431 template <typename T>
434 typedef std::function<T*(void)> CreateFunc;
435 typedef std::function<void(T*)> TeardownFunc;
437 // Generally your program life cycle should be fine with calling
438 // get() repeatedly rather than saving the reference, and then not
439 // call get() during process shutdown.
440 static T* get(SingletonVault* vault = nullptr /* for testing */) {
441 return get_ptr({typeid(T), ""}, vault);
444 static T* get(const char* name,
445 SingletonVault* vault = nullptr /* for testing */) {
446 return get_ptr({typeid(T), name}, vault);
449 // If, however, you do need to hold a reference to the specific
450 // singleton, you can try to do so with a weak_ptr. Avoid this when
451 // possible but the inability to lock the weak pointer can be a
452 // signal that the vault has been destroyed.
453 static std::weak_ptr<T> get_weak(
454 SingletonVault* vault = nullptr /* for testing */) {
455 return get_weak("", vault);
458 static std::weak_ptr<T> get_weak(
459 const char* name, SingletonVault* vault = nullptr /* for testing */) {
461 (vault ?: SingletonVault::singleton())->get_weak({typeid(T), name});
463 // This is ugly and inefficient, but there's no other way to do it, because
464 // there's no static_pointer_cast for weak_ptr.
465 auto shared_void_ptr = weak_void_ptr.lock();
466 if (!shared_void_ptr) {
467 return std::weak_ptr<T>();
469 return std::static_pointer_cast<T>(shared_void_ptr);
472 // Allow the Singleton<t> instance to also retrieve the underlying
473 // singleton, if desired.
474 T* ptr() { return get_ptr(type_descriptor_, vault_); }
475 T& operator*() { return *ptr(); }
476 T* operator->() { return ptr(); }
478 template <typename CreateFunc = std::nullptr_t>
479 explicit Singleton(CreateFunc c = nullptr,
480 Singleton::TeardownFunc t = nullptr,
481 SingletonVault* vault = nullptr /* for testing */)
482 : Singleton({typeid(T), ""}, c, t, vault) {}
484 template <typename CreateFunc = std::nullptr_t>
485 explicit Singleton(const char* name,
486 CreateFunc c = nullptr,
487 Singleton::TeardownFunc t = nullptr,
488 SingletonVault* vault = nullptr /* for testing */)
489 : Singleton({typeid(T), name}, c, t, vault) {}
492 explicit Singleton(detail::TypeDescriptor type,
494 Singleton::TeardownFunc t,
495 SingletonVault* vault) :
497 []() { return new T; },
502 explicit Singleton(detail::TypeDescriptor type,
503 Singleton::CreateFunc c,
504 Singleton::TeardownFunc t,
505 SingletonVault* vault)
506 : type_descriptor_(type) {
508 throw std::logic_error(
509 "nullptr_t should be passed if you want T to be default constructed");
511 SingletonVault::TeardownFunc teardown;
513 teardown = [](void* v) { delete static_cast<T*>(v); };
515 teardown = [t](void* v) { t(static_cast<T*>(v)); };
518 if (vault == nullptr) {
519 vault = SingletonVault::singleton();
522 vault->registerSingleton(type, c, teardown);
525 static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
526 SingletonVault* vault = nullptr /* for testing */) {
527 return static_cast<T*>(
528 (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
531 // Don't use this function, it's private for a reason! Using it
532 // would defeat the *entire purpose* of the vault in that we lose
533 // the ability to guarantee that, after a destroyInstances is
534 // called, all instances are, in fact, destroyed. You should use
535 // weak_ptr if you need to hold a reference to the singleton and
536 // guarantee briefly that it exists.
538 // Yes, you can just get the weak pointer and lock it, but hopefully
539 // if you have taken the time to read this far, you see why that
541 static std::shared_ptr<T> get_shared(
542 detail::TypeDescriptor type_descriptor = {typeid(T), ""},
543 SingletonVault* vault = nullptr /* for testing */) {
544 return std::static_pointer_cast<T>(
545 (vault ?: SingletonVault::singleton())->get_weak(type_descriptor).lock());
548 detail::TypeDescriptor type_descriptor_;
549 SingletonVault* vault_;