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 // The singleton will be created on demand. If the constructor for
38 // MyExpensiveService actually makes use of *another* Singleton, then
39 // the right thing will happen -- that other singleton will complete
40 // construction before get() returns. However, in the event of a
41 // circular dependency, a runtime error will occur.
43 // By default, the singleton instance is constructed via new and
44 // deleted via delete, but this is configurable:
46 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
49 // Where create and destroy are functions, Singleton<T>::CreateFunc
50 // Singleton<T>::TeardownFunc.
52 // What if you need to destroy all of your singletons? Say, some of
53 // your singletons manage threads, but you need to fork? Or your unit
54 // test wants to clean up all global state? Then you can call
55 // SingletonVault::singleton()->destroyInstances(), which invokes the
56 // TeardownFunc for each singleton, in the reverse order they were
57 // created. It is your responsibility to ensure your singletons can
58 // handle cases where the singletons they depend on go away, however.
61 #include <folly/Exception.h>
66 #include <unordered_map>
71 #include <glog/logging.h>
75 // For actual usage, please see the Singleton<T> class at the bottom
76 // of this file; that is what you will actually interact with.
78 // SingletonVault is the class that manages singleton instances. It
79 // is unaware of the underlying types of singletons, and simply
80 // manages lifecycles and invokes CreateFunc and TeardownFunc when
81 // appropriate. In general, you won't need to interact with the
82 // SingletonVault itself.
84 // A vault goes through a few stages of life:
86 // 1. Registration phase; singletons can be registered, but no
87 // singleton can be created.
88 // 2. registrationComplete() has been called; singletons can no
89 // longer be registered, but they can be created.
90 // 3. A vault can return to stage 1 when destroyInstances is called.
92 // In general, you don't need to worry about any of the above; just
93 // ensure registrationComplete() is called near the top of your main()
94 // function, otherwise no singletons can be instantiated.
95 class SingletonVault {
100 typedef std::function<void(void*)> TeardownFunc;
101 typedef std::function<void*(void)> CreateFunc;
103 // Register a singleton of a given type with the create and teardown
105 void registerSingleton(const std::type_info& type,
107 TeardownFunc teardown) {
108 std::lock_guard<std::mutex> guard(mutex_);
110 CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
111 CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
112 auto& entry = singletons_[type];
114 entry.reset(new SingletonEntry);
117 std::lock_guard<std::mutex> entry_guard(entry->mutex_);
118 CHECK(entry->instance == nullptr);
121 entry->create = create;
122 entry->teardown = teardown;
123 entry->state = SingletonEntryState::Dead;
126 // Mark registration is complete; no more singletons can be
127 // registered at this point.
128 void registrationComplete() {
129 std::lock_guard<std::mutex> guard(mutex_);
130 CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
131 state_ = SingletonVaultState::Running;
134 // Destroy all singletons; when complete, the vault can create
135 // singletons once again, or remain dormant.
136 void destroyInstances();
138 // Retrieve a singleton from the vault, creating it if necessary.
139 std::shared_ptr<void> get_shared(const std::type_info& type) {
140 std::unique_lock<std::mutex> lock(mutex_);
141 if (state_ != SingletonVaultState::Running) {
142 throw std::logic_error(
143 "Attempt to load a singleton before "
144 "SingletonVault::registrationComplete was called (hint: you probably "
145 "didn't call initFacebook)");
148 auto it = singletons_.find(type);
149 if (it == singletons_.end()) {
150 throw std::out_of_range(std::string("non-existent singleton: ") +
154 auto& entry = it->second;
155 std::unique_lock<std::mutex> entry_lock(entry->mutex_);
157 if (entry->state == SingletonEntryState::BeingBorn) {
158 throw std::out_of_range(std::string("circular singleton dependency: ") +
162 if (entry->instance == nullptr) {
163 CHECK(entry->state == SingletonEntryState::Dead);
164 entry->state = SingletonEntryState::BeingBorn;
168 // Can't use make_shared -- no support for a custom deleter, sadly.
169 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
173 CHECK(entry->state == SingletonEntryState::BeingBorn);
174 entry->instance = instance;
175 entry->state = SingletonEntryState::Living;
177 creation_order_.push_back(type);
179 CHECK(entry->state == SingletonEntryState::Living);
181 return entry->instance;
184 // For testing; how many registered and living singletons we have.
185 size_t registeredSingletonCount() const {
186 std::lock_guard<std::mutex> guard(mutex_);
187 return singletons_.size();
190 size_t livingSingletonCount() const {
191 std::lock_guard<std::mutex> guard(mutex_);
193 for (const auto& p : singletons_) {
194 if (p.second->instance) {
202 // A well-known vault; you can actually have others, but this is the
204 static SingletonVault* singleton();
207 // The two stages of life for a vault, as mentioned in the class comment.
208 enum class SingletonVaultState {
213 // Each singleton in the vault can be in three states: dead
214 // (registered but never created), being born (running the
215 // CreateFunc), and living (CreateFunc returned an instance).
216 enum class SingletonEntryState {
222 // An actual instance of a singleton, tracking the instance itself,
223 // its state as described above, and the create and teardown
225 struct SingletonEntry {
227 std::shared_ptr<void> instance;
228 CreateFunc create = nullptr;
229 TeardownFunc teardown = nullptr;
230 SingletonEntryState state = SingletonEntryState::Dead;
232 SingletonEntry() = default;
233 SingletonEntry(const SingletonEntry&) = delete;
234 SingletonEntry& operator=(const SingletonEntry&) = delete;
235 SingletonEntry& operator=(SingletonEntry&&) = delete;
236 SingletonEntry(SingletonEntry&&) = delete;
239 mutable std::mutex mutex_;
240 typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
241 std::unordered_map<std::type_index, SingletonEntryPtr> singletons_;
242 std::vector<std::type_index> creation_order_;
243 SingletonVaultState state_ = SingletonVaultState::Registering;
246 // This is the wrapper class that most users actually interact with.
247 // It allows for simple access to registering and instantiating
248 // singletons. Create instances of this class in the global scope of
249 // type Singleton<T> to register your singleton for later access via
250 // Singleton<T>::get().
251 template <typename T>
254 typedef std::function<T*(void)> CreateFunc;
255 typedef std::function<void(T*)> TeardownFunc;
257 // Generally your program life cycle should be fine with calling
258 // get() repeatedly rather than saving the reference, and then not
259 // call get() during process shutdown.
260 static T* get(SingletonVault* vault = nullptr /* for testing */) {
261 return get_shared(vault).get();
264 // If, however, you do need to hold a reference to the specific
265 // singleton, you can try to do so with a weak_ptr. Avoid this when
266 // possible but the inability to lock the weak pointer can be a
267 // signal that the vault has been destroyed.
268 static std::weak_ptr<T> get_weak(SingletonVault* vault =
269 nullptr /* for testing */) {
270 return std::weak_ptr<T>(get_shared(vault));
273 Singleton(Singleton::CreateFunc c = nullptr,
274 Singleton::TeardownFunc t = nullptr,
275 SingletonVault* vault = nullptr /* for testing */) {
277 c = []() { return new T; };
279 SingletonVault::TeardownFunc teardown;
281 teardown = [](void* v) { delete static_cast<T*>(v); };
283 teardown = [t](void* v) { t(static_cast<T*>(v)); };
286 if (vault == nullptr) {
287 vault = SingletonVault::singleton();
290 vault->registerSingleton(typeid(T), c, teardown);
294 // Don't use this function, it's private for a reason! Using it
295 // would defeat the *entire purpose* of the vault in that we lose
296 // the ability to guarantee that, after a destroyInstances is
297 // called, all instances are, in fact, destroyed. You should use
298 // weak_ptr if you need to hold a reference to the singleton and
299 // guarantee briefly that it exists.
301 // Yes, you can just get the weak pointer and lock it, but hopefully
302 // if you have taken the time to read this far, you see why that
304 static std::shared_ptr<T> get_shared(SingletonVault* vault =
305 nullptr /* for testing */) {
306 return std::static_pointer_cast<T>(
307 (vault ?: SingletonVault::singleton())->get_shared(typeid(T)));