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::shared_ptr<void> get_shared(detail::TypeDescriptor type) {
237 auto entry = get_entry_create(type);
238 if (UNLIKELY(!entry)) {
239 return std::shared_ptr<void>();
241 return entry->instance;
244 // This function is inherently racy since we don't hold the
245 // shared_ptr that contains the Singleton. It is the caller's
246 // responsibility to be sane with this, but it is preferable to use
247 // the weak_ptr interface for true safety.
248 void* get_ptr(detail::TypeDescriptor type) {
249 auto entry = get_entry_create(type);
250 if (UNLIKELY(!entry)) {
251 throw std::runtime_error(
252 "Raw pointer to a singleton requested after its destruction.");
254 return entry->instance_ptr;
257 // For testing; how many registered and living singletons we have.
258 size_t registeredSingletonCount() const {
259 RWSpinLock::ReadHolder rh(&mutex_);
261 return singletons_.size();
264 size_t livingSingletonCount() const {
265 RWSpinLock::ReadHolder rh(&mutex_);
268 for (const auto& p : singletons_) {
269 std::lock_guard<std::mutex> entry_guard(p.second->mutex);
270 if (p.second->instance) {
278 // A well-known vault; you can actually have others, but this is the
280 static SingletonVault* singleton();
283 // The two stages of life for a vault, as mentioned in the class comment.
284 enum class SingletonVaultState {
289 // Each singleton in the vault can be in three states: dead
290 // (registered but never created), being born (running the
291 // CreateFunc), and living (CreateFunc returned an instance).
292 enum class SingletonEntryState {
298 void stateCheck(SingletonVaultState expected,
299 const char* msg="Unexpected singleton state change") {
300 if (expected != state_) {
301 throw std::logic_error(msg);
305 // An actual instance of a singleton, tracking the instance itself,
306 // its state as described above, and the create and teardown
308 struct SingletonEntry {
309 // mutex protects the entire entry
312 // state changes notify state_condvar
313 SingletonEntryState state = SingletonEntryState::Dead;
314 std::condition_variable state_condvar;
316 // the thread creating the singleton
317 std::thread::id creating_thread;
319 // The singleton itself and related functions.
320 std::shared_ptr<void> instance;
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 SingletonEntry* get_entry(detail::TypeDescriptor type) {
333 RWSpinLock::ReadHolder rh(&mutex_);
335 auto it = singletons_.find(type);
336 if (it == singletons_.end()) {
337 throw std::out_of_range(std::string("non-existent singleton: ") +
341 return it->second.get();
344 // Get a pointer to the living SingletonEntry for the specified
345 // type. The singleton is created as part of this function, if
347 SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
348 auto entry = get_entry(type);
350 std::unique_lock<std::mutex> entry_lock(entry->mutex);
352 if (entry->state == SingletonEntryState::BeingBorn) {
353 // If this thread is trying to give birth to the singleton, it's
354 // a circular dependency and we must panic.
355 if (entry->creating_thread == std::this_thread::get_id()) {
356 throw std::out_of_range(std::string("circular singleton dependency: ") +
360 entry->state_condvar.wait(entry_lock, [&entry]() {
361 return entry->state != SingletonEntryState::BeingBorn;
365 if (entry->instance == nullptr) {
366 RWSpinLock::ReadHolder rh(&stateMutex_);
367 if (state_ == SingletonVaultState::Quiescing) {
371 CHECK(entry->state == SingletonEntryState::Dead);
372 entry->state = SingletonEntryState::BeingBorn;
373 entry->creating_thread = std::this_thread::get_id();
376 // Can't use make_shared -- no support for a custom deleter, sadly.
377 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
380 CHECK(entry->state == SingletonEntryState::BeingBorn);
381 entry->instance = instance;
382 entry->instance_ptr = instance.get();
383 entry->state = SingletonEntryState::Living;
384 entry->state_condvar.notify_all();
387 RWSpinLock::WriteHolder wh(&mutex_);
389 creation_order_.push_back(type);
392 CHECK(entry->state == SingletonEntryState::Living);
396 mutable folly::RWSpinLock mutex_;
397 typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
398 std::unordered_map<detail::TypeDescriptor,
400 detail::TypeDescriptorHasher> singletons_;
401 std::vector<detail::TypeDescriptor> creation_order_;
402 SingletonVaultState state_{SingletonVaultState::Running};
403 bool registrationComplete_{false};
404 folly::RWSpinLock stateMutex_;
405 Type type_{Type::Relaxed};
408 // This is the wrapper class that most users actually interact with.
409 // It allows for simple access to registering and instantiating
410 // singletons. Create instances of this class in the global scope of
411 // type Singleton<T> to register your singleton for later access via
412 // Singleton<T>::get().
413 template <typename T>
416 typedef std::function<T*(void)> CreateFunc;
417 typedef std::function<void(T*)> TeardownFunc;
419 // Generally your program life cycle should be fine with calling
420 // get() repeatedly rather than saving the reference, and then not
421 // call get() during process shutdown.
422 static T* get(SingletonVault* vault = nullptr /* for testing */) {
423 return get_ptr({typeid(T), ""}, vault);
426 static T* get(const char* name,
427 SingletonVault* vault = nullptr /* for testing */) {
428 return get_ptr({typeid(T), name}, vault);
431 // If, however, you do need to hold a reference to the specific
432 // singleton, you can try to do so with a weak_ptr. Avoid this when
433 // possible but the inability to lock the weak pointer can be a
434 // signal that the vault has been destroyed.
435 static std::weak_ptr<T> get_weak(
436 SingletonVault* vault = nullptr /* for testing */) {
437 return get_weak("", vault);
440 static std::weak_ptr<T> get_weak(
441 const char* name, SingletonVault* vault = nullptr /* for testing */) {
442 return std::weak_ptr<T>(get_shared({typeid(T), name}, vault));
445 // Allow the Singleton<t> instance to also retrieve the underlying
446 // singleton, if desired.
447 T* ptr() { return get_ptr(type_descriptor_, vault_); }
448 T& operator*() { return *ptr(); }
449 T* operator->() { return ptr(); }
451 template <typename CreateFunc = std::nullptr_t>
452 explicit Singleton(CreateFunc c = nullptr,
453 Singleton::TeardownFunc t = nullptr,
454 SingletonVault* vault = nullptr /* for testing */)
455 : Singleton({typeid(T), ""}, c, t, vault) {}
457 template <typename CreateFunc = std::nullptr_t>
458 explicit Singleton(const char* name,
459 CreateFunc c = nullptr,
460 Singleton::TeardownFunc t = nullptr,
461 SingletonVault* vault = nullptr /* for testing */)
462 : Singleton({typeid(T), name}, c, t, vault) {}
465 explicit Singleton(detail::TypeDescriptor type,
467 Singleton::TeardownFunc t,
468 SingletonVault* vault) :
470 []() { return new T; },
475 explicit Singleton(detail::TypeDescriptor type,
476 Singleton::CreateFunc c,
477 Singleton::TeardownFunc t,
478 SingletonVault* vault)
479 : type_descriptor_(type) {
481 throw std::logic_error(
482 "nullptr_t should be passed if you want T to be default constructed");
484 SingletonVault::TeardownFunc teardown;
486 teardown = [](void* v) { delete static_cast<T*>(v); };
488 teardown = [t](void* v) { t(static_cast<T*>(v)); };
491 if (vault == nullptr) {
492 vault = SingletonVault::singleton();
495 vault->registerSingleton(type, c, teardown);
498 static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
499 SingletonVault* vault = nullptr /* for testing */) {
500 return static_cast<T*>(
501 (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
504 // Don't use this function, it's private for a reason! Using it
505 // would defeat the *entire purpose* of the vault in that we lose
506 // the ability to guarantee that, after a destroyInstances is
507 // called, all instances are, in fact, destroyed. You should use
508 // weak_ptr if you need to hold a reference to the singleton and
509 // guarantee briefly that it exists.
511 // Yes, you can just get the weak pointer and lock it, but hopefully
512 // if you have taken the time to read this far, you see why that
514 static std::shared_ptr<T> get_shared(
515 detail::TypeDescriptor type_descriptor = {typeid(T), ""},
516 SingletonVault* vault = nullptr /* for testing */) {
517 return std::static_pointer_cast<T>(
518 (vault ?: SingletonVault::singleton())->get_shared(type_descriptor));
521 detail::TypeDescriptor type_descriptor_;
522 SingletonVault* vault_;