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 CHECK_THROW(state_ == SingletonVaultState::Running, std::logic_error);
143 auto it = singletons_.find(type);
144 if (it == singletons_.end()) {
145 throw std::out_of_range(std::string("non-existent singleton: ") +
149 auto& entry = it->second;
150 std::unique_lock<std::mutex> entry_lock(entry->mutex_);
152 if (entry->state == SingletonEntryState::BeingBorn) {
153 throw std::out_of_range(std::string("circular singleton dependency: ") +
157 if (entry->instance == nullptr) {
158 CHECK(entry->state == SingletonEntryState::Dead);
159 entry->state = SingletonEntryState::BeingBorn;
163 // Can't use make_shared -- no support for a custom deleter, sadly.
164 auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
168 CHECK(entry->state == SingletonEntryState::BeingBorn);
169 entry->instance = instance;
170 entry->state = SingletonEntryState::Living;
172 creation_order_.push_back(type);
174 CHECK(entry->state == SingletonEntryState::Living);
176 return entry->instance;
179 // For testing; how many registered and living singletons we have.
180 size_t registeredSingletonCount() const {
181 std::lock_guard<std::mutex> guard(mutex_);
182 return singletons_.size();
185 size_t livingSingletonCount() const {
186 std::lock_guard<std::mutex> guard(mutex_);
188 for (const auto& p : singletons_) {
189 if (p.second->instance) {
197 // A well-known vault; you can actually have others, but this is the
199 static SingletonVault* singleton();
202 // The two stages of life for a vault, as mentioned in the class comment.
203 enum class SingletonVaultState {
208 // Each singleton in the vault can be in three states: dead
209 // (registered but never created), being born (running the
210 // CreateFunc), and living (CreateFunc returned an instance).
211 enum class SingletonEntryState {
217 // An actual instance of a singleton, tracking the instance itself,
218 // its state as described above, and the create and teardown
220 struct SingletonEntry {
222 std::shared_ptr<void> instance;
223 CreateFunc create = nullptr;
224 TeardownFunc teardown = nullptr;
225 SingletonEntryState state = SingletonEntryState::Dead;
227 SingletonEntry() = default;
228 SingletonEntry(const SingletonEntry&) = delete;
229 SingletonEntry& operator=(const SingletonEntry&) = delete;
230 SingletonEntry& operator=(SingletonEntry&&) = delete;
231 SingletonEntry(SingletonEntry&&) = delete;
234 mutable std::mutex mutex_;
235 typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
236 std::unordered_map<std::type_index, SingletonEntryPtr> singletons_;
237 std::vector<std::type_index> creation_order_;
238 SingletonVaultState state_ = SingletonVaultState::Registering;
241 // This is the wrapper class that most users actually interact with.
242 // It allows for simple access to registering and instantiating
243 // singletons. Create instances of this class in the global scope of
244 // type Singleton<T> to register your singleton for later access via
245 // Singleton<T>::get().
246 template <typename T>
249 typedef std::function<T*(void)> CreateFunc;
250 typedef std::function<void(T*)> TeardownFunc;
252 // Generally your program life cycle should be fine with calling
253 // get() repeatedly rather than saving the reference, and then not
254 // call get() during process shutdown.
255 static T* get(SingletonVault* vault = nullptr /* for testing */) {
256 return get_shared(vault).get();
259 // If, however, you do need to hold a reference to the specific
260 // singleton, you can try to do so with a weak_ptr. Avoid this when
261 // possible but the inability to lock the weak pointer can be a
262 // signal that the vault has been destroyed.
263 static std::weak_ptr<T> get_weak(SingletonVault* vault =
264 nullptr /* for testing */) {
265 return std::weak_ptr<T>(get_shared(vault));
268 Singleton(Singleton::CreateFunc c = nullptr,
269 Singleton::TeardownFunc t = nullptr,
270 SingletonVault* vault = nullptr /* for testing */) {
272 c = []() { return new T; };
274 SingletonVault::TeardownFunc teardown;
276 teardown = [](void* v) { delete static_cast<T*>(v); };
278 teardown = [t](void* v) { t(static_cast<T*>(v)); };
281 if (vault == nullptr) {
282 vault = SingletonVault::singleton();
285 vault->registerSingleton(typeid(T), c, teardown);
289 // Don't use this function, it's private for a reason! Using it
290 // would defeat the *entire purpose* of the vault in that we lose
291 // the ability to guarantee that, after a destroyInstances is
292 // called, all instances are, in fact, destroyed. You should use
293 // weak_ptr if you need to hold a reference to the singleton and
294 // guarantee briefly that it exists.
296 // Yes, you can just get the weak pointer and lock it, but hopefully
297 // if you have taken the time to read this far, you see why that
299 static std::shared_ptr<T> get_shared(SingletonVault* vault =
300 nullptr /* for testing */) {
301 return std::static_pointer_cast<T>(
302 (vault ?: SingletonVault::singleton())->get_shared(typeid(T)));