Try again: folly::Singleton, a class for managing singletons
[folly.git] / folly / experimental / Singleton.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 // SingletonVault - a library to manage the creation and destruction
18 // of interdependent singletons.
19 //
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.
23 //
24 // In your .h file:
25 // class MyExpensiveService { ... };
26 //
27 // In your .cpp file:
28 // namespace { folly::Singleton<MyExpensiveService> the_singleton; }
29 //
30 // Code can access it via:
31 //
32 // MyExpensiveService* instance = Singleton<MyExpensiveService>::get();
33 // or
34 // std::weak_ptr<MyExpensiveService> instance =
35 //     Singleton<MyExpensiveService>::get_weak();
36 //
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.
42 //
43 // By default, the singleton instance is constructed via new and
44 // deleted via delete, but this is configurable:
45 //
46 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
47 //                                                                destroy); }
48 //
49 // Where create and destroy are functions, Singleton<T>::CreateFunc
50 // Singleton<T>::TeardownFunc.
51 //
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.
59
60 #pragma once
61 #include <folly/Exception.h>
62
63 #include <vector>
64 #include <mutex>
65 #include <string>
66 #include <unordered_map>
67 #include <functional>
68 #include <typeinfo>
69 #include <typeindex>
70
71 #include <glog/logging.h>
72
73 namespace folly {
74
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.
77
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.
83 //
84 // A vault goes through a few stages of life:
85 //
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.
91 //
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 {
96  public:
97   SingletonVault() {};
98   ~SingletonVault();
99
100   typedef std::function<void(void*)> TeardownFunc;
101   typedef std::function<void*(void)> CreateFunc;
102
103   // Register a singleton of a given type with the create and teardown
104   // functions.
105   void registerSingleton(const std::type_info& type,
106                          CreateFunc create,
107                          TeardownFunc teardown) {
108     std::lock_guard<std::mutex> guard(mutex_);
109
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];
113     if (!entry) {
114       entry.reset(new SingletonEntry);
115     }
116
117     std::lock_guard<std::mutex> entry_guard(entry->mutex_);
118     CHECK(entry->instance == nullptr);
119     CHECK(create);
120     CHECK(teardown);
121     entry->create = create;
122     entry->teardown = teardown;
123     entry->state = SingletonEntryState::Dead;
124   }
125
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;
132   }
133
134   // Destroy all singletons; when complete, the vault can create
135   // singletons once again, or remain dormant.
136   void destroyInstances();
137
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);
142
143     auto it = singletons_.find(type);
144     if (it == singletons_.end()) {
145       throw std::out_of_range(std::string("non-existent singleton: ") +
146                               type.name());
147     }
148
149     auto& entry = it->second;
150     std::unique_lock<std::mutex> entry_lock(entry->mutex_);
151
152     if (entry->state == SingletonEntryState::BeingBorn) {
153       throw std::out_of_range(std::string("circular singleton dependency: ") +
154                               type.name());
155     }
156
157     if (entry->instance == nullptr) {
158       CHECK(entry->state == SingletonEntryState::Dead);
159       entry->state = SingletonEntryState::BeingBorn;
160
161       entry_lock.unlock();
162       lock.unlock();
163       // Can't use make_shared -- no support for a custom deleter, sadly.
164       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
165       lock.lock();
166       entry_lock.lock();
167
168       CHECK(entry->state == SingletonEntryState::BeingBorn);
169       entry->instance = instance;
170       entry->state = SingletonEntryState::Living;
171
172       creation_order_.push_back(type);
173     }
174     CHECK(entry->state == SingletonEntryState::Living);
175
176     return entry->instance;
177   }
178
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();
183   }
184
185   size_t livingSingletonCount() const {
186     std::lock_guard<std::mutex> guard(mutex_);
187     size_t ret = 0;
188     for (const auto& p : singletons_) {
189       if (p.second->instance) {
190         ++ret;
191       }
192     }
193
194     return ret;
195   }
196
197   // A well-known vault; you can actually have others, but this is the
198   // default.
199   static SingletonVault* singleton();
200
201  private:
202   // The two stages of life for a vault, as mentioned in the class comment.
203   enum class SingletonVaultState {
204     Registering,
205     Running,
206   };
207
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 {
212     Dead,
213     BeingBorn,
214     Living,
215   };
216
217   // An actual instance of a singleton, tracking the instance itself,
218   // its state as described above, and the create and teardown
219   // functions.
220   struct SingletonEntry {
221     std::mutex mutex_;
222     std::shared_ptr<void> instance;
223     CreateFunc create = nullptr;
224     TeardownFunc teardown = nullptr;
225     SingletonEntryState state = SingletonEntryState::Dead;
226
227     SingletonEntry() = default;
228     SingletonEntry(const SingletonEntry&) = delete;
229     SingletonEntry& operator=(const SingletonEntry&) = delete;
230     SingletonEntry& operator=(SingletonEntry&&) = delete;
231     SingletonEntry(SingletonEntry&&) = delete;
232   };
233
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;
239 };
240
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>
247 class Singleton {
248  public:
249   typedef std::function<T*(void)> CreateFunc;
250   typedef std::function<void(T*)> TeardownFunc;
251
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();
257   }
258
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));
266   }
267
268   Singleton(Singleton::CreateFunc c = nullptr,
269             Singleton::TeardownFunc t = nullptr,
270             SingletonVault* vault = nullptr /* for testing */) {
271     if (c == nullptr) {
272       c = []() { return new T; };
273     }
274     SingletonVault::TeardownFunc teardown;
275     if (t == nullptr) {
276       teardown = [](void* v) { delete static_cast<T*>(v); };
277     } else {
278       teardown = [t](void* v) { t(static_cast<T*>(v)); };
279     }
280
281     if (vault == nullptr) {
282       vault = SingletonVault::singleton();
283     }
284
285     vault->registerSingleton(typeid(T), c, teardown);
286   }
287
288  private:
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.
295   //
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
298   // would be bad.
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)));
303   }
304 };
305 }