2 * Copyright 2015 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 tag. If no tag is specified - default tag is used
56 // folly::Singleton<MyExpensiveService> s_default;
57 // folly::Singleton<MyExpensiveService, Tag1> s1;
58 // folly::Singleton<MyExpensiveService, Tag2> s2;
61 // MyExpensiveService* svc_default = s_default.get();
62 // MyExpensiveService* svc1 = s1.get();
63 // MyExpensiveService* svc2 = s2.get();
65 // By default, the singleton instance is constructed via new and
66 // deleted via delete, but this is configurable:
68 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
71 // Where create and destroy are functions, Singleton<T>::CreateFunc
72 // Singleton<T>::TeardownFunc.
74 // The above examples detail a situation where an expensive singleton is loaded
75 // on-demand (thus only if needed). However if there is an expensive singleton
76 // that will likely be needed, and initialization takes a potentially long time,
77 // e.g. while initializing, parsing some files, talking to remote services,
78 // making uses of other singletons, and so on, the initialization of those can
79 // be scheduled up front, or "eagerly".
81 // In that case the singleton can be declared this way:
84 // auto the_singleton =
85 // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
86 // .shouldEagerInit();
89 // This way the singleton's instance is built at program initialization
90 // time, or more accurately, when "registrationComplete()" or
91 // "startEagerInit()" is called. (More about that below; see the
92 // section starting with "A vault goes through a few stages of life".)
94 // What if you need to destroy all of your singletons? Say, some of
95 // your singletons manage threads, but you need to fork? Or your unit
96 // test wants to clean up all global state? Then you can call
97 // SingletonVault::singleton()->destroyInstances(), which invokes the
98 // TeardownFunc for each singleton, in the reverse order they were
99 // created. It is your responsibility to ensure your singletons can
100 // handle cases where the singletons they depend on go away, however.
101 // Singletons won't be recreated after destroyInstances call. If you
102 // want to re-enable singleton creation (say after fork was called) you
103 // should call reenableInstances.
106 #include <folly/Baton.h>
107 #include <folly/Exception.h>
108 #include <folly/Hash.h>
109 #include <folly/Memory.h>
110 #include <folly/RWSpinLock.h>
111 #include <folly/Demangle.h>
112 #include <folly/Executor.h>
113 #include <folly/io/async/Request.h>
119 #include <condition_variable>
121 #include <unordered_map>
122 #include <unordered_set>
123 #include <functional>
127 #include <glog/logging.h>
129 // use this guard to handleSingleton breaking change in 3rd party code
130 #ifndef FOLLY_SINGLETON_TRY_GET
131 #define FOLLY_SINGLETON_TRY_GET
136 // For actual usage, please see the Singleton<T> class at the bottom
137 // of this file; that is what you will actually interact with.
139 // SingletonVault is the class that manages singleton instances. It
140 // is unaware of the underlying types of singletons, and simply
141 // manages lifecycles and invokes CreateFunc and TeardownFunc when
142 // appropriate. In general, you won't need to interact with the
143 // SingletonVault itself.
145 // A vault goes through a few stages of life:
147 // 1. Registration phase; singletons can be registered, but no
148 // singleton can be created.
149 // 2. registrationComplete() has been called; singletons can no
150 // longer be registered, but they can be created.
151 // 3. A vault can return to stage 1 when destroyInstances is called.
153 // In general, you don't need to worry about any of the above; just
154 // ensure registrationComplete() is called near the top of your main()
155 // function, otherwise no singletons can be instantiated.
157 class SingletonVault;
161 struct DefaultTag {};
163 // A TypeDescriptor is the unique handle for a given singleton. It is
164 // a combinaiton of the type and of the optional name, and is used as
165 // a key in unordered_maps.
166 class TypeDescriptor {
168 TypeDescriptor(const std::type_info& ti,
169 const std::type_info& tag_ti)
170 : ti_(ti), tag_ti_(tag_ti) {
173 TypeDescriptor(const TypeDescriptor& other)
174 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
177 TypeDescriptor& operator=(const TypeDescriptor& other) {
178 if (this != &other) {
180 tag_ti_ = other.tag_ti_;
186 std::string name() const {
187 auto ret = demangle(ti_.name());
188 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
190 ret += demangle(tag_ti_.name());
192 return ret.toStdString();
195 friend class TypeDescriptorHasher;
197 bool operator==(const TypeDescriptor& other) const {
198 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
203 std::type_index tag_ti_;
206 class TypeDescriptorHasher {
208 size_t operator()(const TypeDescriptor& ti) const {
209 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
213 // This interface is used by SingletonVault to interact with SingletonHolders.
214 // Having a non-template interface allows SingletonVault to keep a list of all
216 class SingletonHolderBase {
218 virtual ~SingletonHolderBase() = default;
220 virtual TypeDescriptor type() = 0;
221 virtual bool hasLiveInstance() = 0;
222 virtual void createInstance() = 0;
223 virtual bool creationStarted() = 0;
224 virtual void destroyInstance() = 0;
227 static constexpr std::chrono::seconds kDestroyWaitTime{5};
230 // An actual instance of a singleton, tracking the instance itself,
231 // its state as described above, and the create and teardown
233 template <typename T>
234 struct SingletonHolder : public SingletonHolderBase {
236 typedef std::function<void(T*)> TeardownFunc;
237 typedef std::function<T*(void)> CreateFunc;
239 template <typename Tag, typename VaultTag>
240 inline static SingletonHolder<T>& singleton();
243 inline std::weak_ptr<T> get_weak();
245 void registerSingleton(CreateFunc c, TeardownFunc t);
246 void registerSingletonMock(CreateFunc c, TeardownFunc t);
247 virtual TypeDescriptor type() override;
248 virtual bool hasLiveInstance() override;
249 virtual void createInstance() override;
250 virtual bool creationStarted() override;
251 virtual void destroyInstance() override;
254 SingletonHolder(TypeDescriptor type, SingletonVault& vault);
256 enum class SingletonHolderState {
262 TypeDescriptor type_;
263 SingletonVault& vault_;
265 // mutex protects the entire entry during construction/destruction
268 // State of the singleton entry. If state is Living, instance_ptr and
269 // instance_weak can be safely accessed w/o synchronization.
270 std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
272 // the thread creating the singleton (only valid while creating an object)
273 std::atomic<std::thread::id> creating_thread_;
275 // The singleton itself and related functions.
277 // holds a shared_ptr to singleton instance, set when state is changed from
278 // Dead to Living. Reset when state is changed from Living to Dead.
279 std::shared_ptr<T> instance_;
280 // weak_ptr to the singleton instance, set when state is changed from Dead
281 // to Living. We never write to this object after initialization, so it is
282 // safe to read it from different threads w/o synchronization if we know
283 // that state is set to Living
284 std::weak_ptr<T> instance_weak_;
285 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
286 std::shared_ptr<folly::Baton<>> destroy_baton_;
287 T* instance_ptr_ = nullptr;
288 CreateFunc create_ = nullptr;
289 TeardownFunc teardown_ = nullptr;
291 std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
293 SingletonHolder(const SingletonHolder&) = delete;
294 SingletonHolder& operator=(const SingletonHolder&) = delete;
295 SingletonHolder& operator=(SingletonHolder&&) = delete;
296 SingletonHolder(SingletonHolder&&) = delete;
301 class SingletonVault {
303 enum class Type { Strict, Relaxed };
305 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
307 // Destructor is only called by unit tests to check destroyInstances.
310 typedef std::function<void(void*)> TeardownFunc;
311 typedef std::function<void*(void)> CreateFunc;
313 // Ensure that Singleton has not been registered previously and that
314 // registration is not complete. If validations succeeds,
315 // register a singleton of a given type with the create and teardown
317 void registerSingleton(detail::SingletonHolderBase* entry) {
318 RWSpinLock::ReadHolder rh(&stateMutex_);
320 stateCheck(SingletonVaultState::Running);
322 if (UNLIKELY(registrationComplete_)) {
323 throw std::logic_error(
324 "Registering singleton after registrationComplete().");
327 RWSpinLock::ReadHolder rhMutex(&mutex_);
328 CHECK_THROW(singletons_.find(entry->type()) == singletons_.end(),
331 RWSpinLock::UpgradedHolder wh(&mutex_);
332 singletons_[entry->type()] = entry;
336 * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
337 * is built when registrationComplete() is called; see that method
340 void addEagerInitSingleton(detail::SingletonHolderBase* entry) {
341 RWSpinLock::ReadHolder rh(&stateMutex_);
343 stateCheck(SingletonVaultState::Running);
345 if (UNLIKELY(registrationComplete_)) {
346 throw std::logic_error(
347 "Registering for eager-load after registrationComplete().");
350 RWSpinLock::ReadHolder rhMutex(&mutex_);
351 CHECK_THROW(singletons_.find(entry->type()) != singletons_.end(),
354 RWSpinLock::UpgradedHolder wh(&mutex_);
355 eagerInitSingletons_.insert(entry);
358 // Mark registration is complete; no more singletons can be
359 // registered at this point. Kicks off eagerly-initialized singletons
360 // (if requested; default behavior is to do so).
361 void registrationComplete(bool autoStartEagerInit = true) {
362 RequestContext::saveContext();
363 std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
366 RWSpinLock::WriteHolder wh(&stateMutex_);
368 stateCheck(SingletonVaultState::Running);
370 if (type_ == Type::Strict) {
371 for (const auto& p: singletons_) {
372 if (p.second->hasLiveInstance()) {
373 throw std::runtime_error(
374 "Singleton created before registration was complete.");
379 registrationComplete_ = true;
382 if (autoStartEagerInit) {
388 * If eagerInitExecutor_ is non-nullptr (default is nullptr) then
389 * schedule eager singletons' initializations through it.
390 * Otherwise, initializes them synchronously, in a loop.
392 void startEagerInit() {
393 std::unordered_set<detail::SingletonHolderBase*> singletonSet;
395 RWSpinLock::ReadHolder rh(&stateMutex_);
396 stateCheck(SingletonVaultState::Running);
397 if (UNLIKELY(!registrationComplete_)) {
398 throw std::logic_error(
399 "registrationComplete() not yet called");
401 singletonSet = eagerInitSingletons_; // copy set of pointers
404 auto *exe = eagerInitExecutor_; // default value is nullptr
405 for (auto *single : singletonSet) {
407 eagerInitExecutor_->add([single] {
408 if (!single->creationStarted()) {
409 single->createInstance();
413 single->createInstance();
419 * Provide an executor through which startEagerInit would run tasks.
420 * If there are several singletons which may be independently initialized,
421 * and their construction takes long, they could possibly be run in parallel
422 * to cut down on startup time. Unusual; default (synchronous initialization
423 * in a loop) is probably fine for most use cases, and most apps can most
424 * likely avoid using this.
426 void setEagerInitExecutor(folly::Executor *exe) {
427 eagerInitExecutor_ = exe;
430 // Destroy all singletons; when complete, the vault can't create
431 // singletons once again until reenableInstances() is called.
432 void destroyInstances();
434 // Enable re-creating singletons after destroyInstances() was called.
435 void reenableInstances();
437 // For testing; how many registered and living singletons we have.
438 size_t registeredSingletonCount() const {
439 RWSpinLock::ReadHolder rh(&mutex_);
441 return singletons_.size();
444 size_t livingSingletonCount() const {
445 RWSpinLock::ReadHolder rh(&mutex_);
448 for (const auto& p : singletons_) {
449 if (p.second->hasLiveInstance()) {
457 // A well-known vault; you can actually have others, but this is the
459 static SingletonVault* singleton() {
460 return singleton<>();
463 // Gets singleton vault for any Tag. Non-default tag should be used in unit
465 template <typename VaultTag = detail::DefaultTag>
466 static SingletonVault* singleton() {
467 static SingletonVault* vault = new SingletonVault();
471 typedef std::string(*StackTraceGetterPtr)();
473 static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
474 static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
475 return stackTraceGetterPtr;
479 template <typename T>
480 friend struct detail::SingletonHolder;
482 // The two stages of life for a vault, as mentioned in the class comment.
483 enum class SingletonVaultState {
488 // Each singleton in the vault can be in two states: dead
489 // (registered but never created), living (CreateFunc returned an instance).
491 void stateCheck(SingletonVaultState expected,
492 const char* msg="Unexpected singleton state change") {
493 if (expected != state_) {
494 throw std::logic_error(msg);
498 // This method only matters if registrationComplete() is never called.
499 // Otherwise destroyInstances is scheduled to be executed atexit.
501 // Initializes static object, which calls destroyInstances on destruction.
502 // Used to have better deletion ordering with singleton not managed by
503 // folly::Singleton. The desruction will happen in the following order:
504 // 1. Singletons, not managed by folly::Singleton, which were created after
505 // any of the singletons managed by folly::Singleton was requested.
506 // 2. All singletons managed by folly::Singleton
507 // 3. Singletons, not managed by folly::Singleton, which were created before
508 // any of the singletons managed by folly::Singleton was requested.
509 static void scheduleDestroyInstances();
511 typedef std::unordered_map<detail::TypeDescriptor,
512 detail::SingletonHolderBase*,
513 detail::TypeDescriptorHasher> SingletonMap;
515 mutable folly::RWSpinLock mutex_;
516 SingletonMap singletons_;
517 std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
518 folly::Executor* eagerInitExecutor_{nullptr};
519 std::vector<detail::TypeDescriptor> creation_order_;
520 SingletonVaultState state_{SingletonVaultState::Running};
521 bool registrationComplete_{false};
522 folly::RWSpinLock stateMutex_;
523 Type type_{Type::Relaxed};
526 // This is the wrapper class that most users actually interact with.
527 // It allows for simple access to registering and instantiating
528 // singletons. Create instances of this class in the global scope of
529 // type Singleton<T> to register your singleton for later access via
530 // Singleton<T>::try_get().
531 template <typename T,
532 typename Tag = detail::DefaultTag,
533 typename VaultTag = detail::DefaultTag /* for testing */>
536 typedef std::function<T*(void)> CreateFunc;
537 typedef std::function<void(T*)> TeardownFunc;
539 // Generally your program life cycle should be fine with calling
540 // get() repeatedly rather than saving the reference, and then not
541 // call get() during process shutdown.
542 static T* get() __attribute__ ((__deprecated__("Replaced by try_get"))) {
543 return getEntry().get();
546 // If, however, you do need to hold a reference to the specific
547 // singleton, you can try to do so with a weak_ptr. Avoid this when
548 // possible but the inability to lock the weak pointer can be a
549 // signal that the vault has been destroyed.
550 static std::weak_ptr<T> get_weak() {
551 return getEntry().get_weak();
554 // Preferred alternative to get_weak, it returns shared_ptr that can be
555 // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
556 // Avoid holding these shared_ptrs beyond the scope of a function;
557 // don't put them in member variables, always use try_get() instead
558 static std::shared_ptr<T> try_get() {
559 auto ret = get_weak().lock();
562 "folly::Singleton<" << getEntry().type().name() <<
563 ">::get_weak() called on destructed singleton; "
564 "returning nullptr, possible segfault coming";
569 explicit Singleton(std::nullptr_t _ = nullptr,
570 typename Singleton::TeardownFunc t = nullptr) :
571 Singleton ([]() { return new T; }, std::move(t)) {
574 explicit Singleton(typename Singleton::CreateFunc c,
575 typename Singleton::TeardownFunc t = nullptr) {
577 throw std::logic_error(
578 "nullptr_t should be passed if you want T to be default constructed");
581 auto vault = SingletonVault::singleton<VaultTag>();
582 getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
583 vault->registerSingleton(&getEntry());
587 * Should be instantiated as soon as "registrationComplete()" is called.
588 * Singletons are usually lazy-loaded (built on-demand) but for those which
589 * are known to be needed, to avoid the potential lag for objects that take
590 * long to construct during runtime, there is an option to make sure these
591 * are built up-front.
594 * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
596 * Or alternately, define the singleton as usual, and say
597 * gFooInstance.shouldEagerInit()
599 * at some point prior to calling registrationComplete().
600 * Then registrationComplete can be called (by default it will kick off
601 * init of the eager singletons); alternately, you can use
604 Singleton& shouldEagerInit() {
605 auto vault = SingletonVault::singleton<VaultTag>();
606 vault->addEagerInitSingleton(&getEntry());
611 * Construct and inject a mock singleton which should be used only from tests.
612 * Unlike regular singletons which are initialized once per process lifetime,
613 * mock singletons live for the duration of a test. This means that one process
614 * running multiple tests can initialize and register the same singleton
615 * multiple times. This functionality should be used only from tests
616 * since it relaxes validation and performance in order to be able to perform
617 * the injection. The returned mock singleton is functionality identical to
618 * regular singletons.
620 static void make_mock(std::nullptr_t c = nullptr,
621 typename Singleton<T>::TeardownFunc t = nullptr) {
622 make_mock([]() { return new T; }, t);
625 static void make_mock(CreateFunc c,
626 typename Singleton<T>::TeardownFunc t = nullptr) {
628 throw std::logic_error(
629 "nullptr_t should be passed if you want T to be default constructed");
632 auto& entry = getEntry();
634 entry.registerSingletonMock(c, getTeardownFunc(t));
638 inline static detail::SingletonHolder<T>& getEntry() {
639 return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
642 // Construct TeardownFunc.
643 static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
646 return [](T* v) { delete v; };
655 #include <folly/Singleton-inl.h>