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.
79 #include <folly/Exception.h>
80 #include <folly/Hash.h>
81 #include <folly/RWSpinLock.h>
86 #include <condition_variable>
88 #include <unordered_map>
93 #include <glog/logging.h>
97 // For actual usage, please see the Singleton<T> class at the bottom
98 // of this file; that is what you will actually interact with.
100 // SingletonVault is the class that manages singleton instances. It
101 // is unaware of the underlying types of singletons, and simply
102 // manages lifecycles and invokes CreateFunc and TeardownFunc when
103 // appropriate. In general, you won't need to interact with the
104 // SingletonVault itself.
106 // A vault goes through a few stages of life:
108 // 1. Registration phase; singletons can be registered, but no
109 // singleton can be created.
110 // 2. registrationComplete() has been called; singletons can no
111 // longer be registered, but they can be created.
112 // 3. A vault can return to stage 1 when destroyInstances is called.
114 // In general, you don't need to worry about any of the above; just
115 // ensure registrationComplete() is called near the top of your main()
116 // function, otherwise no singletons can be instantiated.
120 const char* const kDefaultTypeDescriptorName = "(default)";
121 // A TypeDescriptor is the unique handle for a given singleton. It is
122 // a combinaiton of the type and of the optional name, and is used as
123 // a key in unordered_maps.
124 class TypeDescriptor {
126 TypeDescriptor(const std::type_info& ti, std::string name)
127 : ti_(ti), name_(name) {
128 if (name_ == kDefaultTypeDescriptorName) {
129 LOG(DFATAL) << "Caller used the default name as their literal name; "
130 << "name your singleton something other than "
131 << kDefaultTypeDescriptorName;
135 std::string name() const {
136 std::string ret = ti_.name();
139 ret += kDefaultTypeDescriptorName;
146 friend class TypeDescriptorHasher;
148 bool operator==(const TypeDescriptor& other) const {
149 return ti_ == other.ti_ && name_ == other.name_;
153 const std::type_index ti_;
154 const std::string name_;
157 class TypeDescriptorHasher {
159 size_t operator()(const TypeDescriptor& ti) const {
160 return folly::hash::hash_combine(ti.ti_, ti.name_);
165 class SingletonVault {
167 enum class Type { Strict, Relaxed };
169 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
172 typedef std::function<void(void*)> TeardownFunc;
173 typedef std::function<void*(void)> CreateFunc;
175 // Register a singleton of a given type with the create and teardown
177 void registerSingleton(detail::TypeDescriptor type,
179 TeardownFunc teardown) {
180 RWSpinLock::WriteHolder wh(&mutex_);
182 stateCheck(SingletonVaultState::Registering);
183 CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
184 auto& entry = singletons_[type];
185 entry.reset(new SingletonEntry);
187 std::lock_guard<std::mutex> entry_guard(entry->mutex);
188 CHECK(entry->instance == nullptr);
191 entry->create = create;
192 entry->teardown = teardown;
193 entry->state = SingletonEntryState::Dead;
196 // Mark registration is complete; no more singletons can be
197 // registered at this point.
198 void registrationComplete() {
199 RWSpinLock::WriteHolder wh(&mutex_);
201 stateCheck(SingletonVaultState::Registering);
202 state_ = SingletonVaultState::Running;
205 // Destroy all singletons; when complete, the vault can create
206 // singletons once again, or remain dormant.
207 void destroyInstances();
209 // Retrieve a singleton from the vault, creating it if necessary.
210 std::shared_ptr<void> get_shared(detail::TypeDescriptor type) {
211 auto entry = get_entry_create(type);
212 return entry->instance;
215 // This function is inherently racy since we don't hold the
216 // shared_ptr that contains the Singleton. It is the caller's
217 // responsibility to be sane with this, but it is preferable to use
218 // the weak_ptr interface for true safety.
219 void* get_ptr(detail::TypeDescriptor type) {
220 auto entry = get_entry_create(type);
221 return entry->instance_ptr;
224 // For testing; how many registered and living singletons we have.
225 size_t registeredSingletonCount() const {
226 RWSpinLock::ReadHolder rh(&mutex_);
228 return singletons_.size();
231 size_t livingSingletonCount() const {
232 RWSpinLock::ReadHolder rh(&mutex_);
235 for (const auto& p : singletons_) {
236 std::lock_guard<std::mutex> entry_guard(p.second->mutex);
237 if (p.second->instance) {
245 // A well-known vault; you can actually have others, but this is the
247 static SingletonVault* singleton();
250 // The two stages of life for a vault, as mentioned in the class comment.
251 enum class SingletonVaultState {
256 // Each singleton in the vault can be in three states: dead
257 // (registered but never created), being born (running the
258 // CreateFunc), and living (CreateFunc returned an instance).
259 enum class SingletonEntryState {
265 void stateCheck(SingletonVaultState expected,
266 const char* msg="Unexpected singleton state change") {
267 if (type_ == Type::Strict && expected != state_) {
268 throw std::logic_error(msg);
272 // An actual instance of a singleton, tracking the instance itself,
273 // its state as described above, and the create and teardown
275 struct SingletonEntry {
276 // mutex protects the entire entry
279 // state changes notify state_condvar
280 SingletonEntryState state = SingletonEntryState::Dead;
281 std::condition_variable state_condvar;
283 // the thread creating the singleton
284 std::thread::id creating_thread;
286 // The singleton itself and related functions.
287 std::shared_ptr<void> instance;
288 void* instance_ptr = nullptr;
289 CreateFunc create = nullptr;
290 TeardownFunc teardown = nullptr;
292 SingletonEntry() = default;
293 SingletonEntry(const SingletonEntry&) = delete;
294 SingletonEntry& operator=(const SingletonEntry&) = delete;
295 SingletonEntry& operator=(SingletonEntry&&) = delete;
296 SingletonEntry(SingletonEntry&&) = delete;
299 SingletonEntry* get_entry(detail::TypeDescriptor type) {
300 RWSpinLock::ReadHolder rh(&mutex_);
302 // mutex must be held when calling this function
304 SingletonVaultState::Running,
305 "Attempt to load a singleton before "
306 "SingletonVault::registrationComplete was called (hint: you probably "
307 "didn't call initFacebook)");
309 auto it = singletons_.find(type);
310 if (it == singletons_.end()) {
311 throw std::out_of_range(std::string("non-existent singleton: ") +
315 return it->second.get();
318 // Get a pointer to the living SingletonEntry for the specified
319 // type. The singleton is created as part of this function, if
321 SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
322 auto entry = get_entry(type);
324 std::unique_lock<std::mutex> entry_lock(entry->mutex);
326 if (entry->state == SingletonEntryState::BeingBorn) {
327 // If this thread is trying to give birth to the singleton, it's
328 // a circular dependency and we must panic.
329 if (entry->creating_thread == std::this_thread::get_id()) {
330 throw std::out_of_range(std::string("circular singleton dependency: ") +
334 entry->state_condvar.wait(entry_lock, [&entry]() {
335 return entry->state != SingletonEntryState::BeingBorn;
339 if (entry->instance == nullptr) {
340 CHECK(entry->state == SingletonEntryState::Dead);
341 entry->state = SingletonEntryState::BeingBorn;
342 entry->creating_thread = std::this_thread::get_id();
345 // Can't use make_shared -- no support for a custom deleter, sadly.
346 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
349 CHECK(entry->state == SingletonEntryState::BeingBorn);
350 entry->instance = instance;
351 entry->instance_ptr = instance.get();
352 entry->state = SingletonEntryState::Living;
353 entry->state_condvar.notify_all();
356 RWSpinLock::WriteHolder wh(&mutex_);
358 creation_order_.push_back(type);
361 CHECK(entry->state == SingletonEntryState::Living);
365 mutable folly::RWSpinLock mutex_;
366 typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
367 std::unordered_map<detail::TypeDescriptor,
369 detail::TypeDescriptorHasher> singletons_;
370 std::vector<detail::TypeDescriptor> creation_order_;
371 SingletonVaultState state_ = SingletonVaultState::Registering;
372 Type type_ = Type::Relaxed;
375 // This is the wrapper class that most users actually interact with.
376 // It allows for simple access to registering and instantiating
377 // singletons. Create instances of this class in the global scope of
378 // type Singleton<T> to register your singleton for later access via
379 // Singleton<T>::get().
380 template <typename T>
383 typedef std::function<T*(void)> CreateFunc;
384 typedef std::function<void(T*)> TeardownFunc;
386 // Generally your program life cycle should be fine with calling
387 // get() repeatedly rather than saving the reference, and then not
388 // call get() during process shutdown.
389 static T* get(SingletonVault* vault = nullptr /* for testing */) {
390 return get_ptr({typeid(T), ""}, vault);
393 static T* get(const char* name,
394 SingletonVault* vault = nullptr /* for testing */) {
395 return get_ptr({typeid(T), name}, vault);
398 // If, however, you do need to hold a reference to the specific
399 // singleton, you can try to do so with a weak_ptr. Avoid this when
400 // possible but the inability to lock the weak pointer can be a
401 // signal that the vault has been destroyed.
402 static std::weak_ptr<T> get_weak(
403 SingletonVault* vault = nullptr /* for testing */) {
404 return get_weak("", vault);
407 static std::weak_ptr<T> get_weak(
408 const char* name, SingletonVault* vault = nullptr /* for testing */) {
409 return std::weak_ptr<T>(get_shared({typeid(T), name}, vault));
412 // Allow the Singleton<t> instance to also retrieve the underlying
413 // singleton, if desired.
414 T* ptr() { return get_ptr(type_descriptor_, vault_); }
415 T& operator*() { return *ptr(); }
416 T* operator->() { return ptr(); }
418 explicit Singleton(Singleton::CreateFunc c = nullptr,
419 Singleton::TeardownFunc t = nullptr,
420 SingletonVault* vault = nullptr /* for testing */)
421 : Singleton({typeid(T), ""}, c, t, vault) {}
423 explicit Singleton(const char* name,
424 Singleton::CreateFunc c = nullptr,
425 Singleton::TeardownFunc t = nullptr,
426 SingletonVault* vault = nullptr /* for testing */)
427 : Singleton({typeid(T), name}, c, t, vault) {}
430 explicit Singleton(detail::TypeDescriptor type,
431 Singleton::CreateFunc c = nullptr,
432 Singleton::TeardownFunc t = nullptr,
433 SingletonVault* vault = nullptr /* for testing */)
434 : type_descriptor_(type) {
436 c = []() { return new T; };
438 SingletonVault::TeardownFunc teardown;
440 teardown = [](void* v) { delete static_cast<T*>(v); };
442 teardown = [t](void* v) { t(static_cast<T*>(v)); };
445 if (vault == nullptr) {
446 vault = SingletonVault::singleton();
449 vault->registerSingleton(type, c, teardown);
452 static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
453 SingletonVault* vault = nullptr /* for testing */) {
454 return static_cast<T*>(
455 (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
458 // Don't use this function, it's private for a reason! Using it
459 // would defeat the *entire purpose* of the vault in that we lose
460 // the ability to guarantee that, after a destroyInstances is
461 // called, all instances are, in fact, destroyed. You should use
462 // weak_ptr if you need to hold a reference to the singleton and
463 // guarantee briefly that it exists.
465 // Yes, you can just get the weak pointer and lock it, but hopefully
466 // if you have taken the time to read this far, you see why that
468 static std::shared_ptr<T> get_shared(
469 detail::TypeDescriptor type_descriptor = {typeid(T), ""},
470 SingletonVault* vault = nullptr /* for testing */) {
471 return std::static_pointer_cast<T>(
472 (vault ?: SingletonVault::singleton())->get_shared(type_descriptor));
475 detail::TypeDescriptor type_descriptor_;
476 SingletonVault* vault_;