2 * Copyright 2016 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 // if the program opted-in to that feature by calling "doEagerInit" or
91 // "doEagerInitVia" during its startup.
93 // What if you need to destroy all of your singletons? Say, some of
94 // your singletons manage threads, but you need to fork? Or your unit
95 // test wants to clean up all global state? Then you can call
96 // SingletonVault::singleton()->destroyInstances(), which invokes the
97 // TeardownFunc for each singleton, in the reverse order they were
98 // created. It is your responsibility to ensure your singletons can
99 // handle cases where the singletons they depend on go away, however.
100 // Singletons won't be recreated after destroyInstances call. If you
101 // want to re-enable singleton creation (say after fork was called) you
102 // should call reenableInstances.
105 #include <folly/Baton.h>
106 #include <folly/Exception.h>
107 #include <folly/Hash.h>
108 #include <folly/Memory.h>
109 #include <folly/RWSpinLock.h>
110 #include <folly/Demangle.h>
111 #include <folly/Executor.h>
112 #include <folly/experimental/ReadMostlySharedPtr.h>
113 #include <folly/detail/StaticSingletonManager.h>
117 #include <condition_variable>
118 #include <functional>
125 #include <unordered_map>
126 #include <unordered_set>
129 #include <glog/logging.h>
131 // use this guard to handleSingleton breaking change in 3rd party code
132 #ifndef FOLLY_SINGLETON_TRY_GET
133 #define FOLLY_SINGLETON_TRY_GET
138 // For actual usage, please see the Singleton<T> class at the bottom
139 // of this file; that is what you will actually interact with.
141 // SingletonVault is the class that manages singleton instances. It
142 // is unaware of the underlying types of singletons, and simply
143 // manages lifecycles and invokes CreateFunc and TeardownFunc when
144 // appropriate. In general, you won't need to interact with the
145 // SingletonVault itself.
147 // A vault goes through a few stages of life:
149 // 1. Registration phase; singletons can be registered:
150 // a) Strict: no singleton can be created in this stage.
151 // b) Relaxed: singleton can be created (the default vault is Relaxed).
152 // 2. registrationComplete() has been called; singletons can no
153 // longer be registered, but they can be created.
154 // 3. A vault can return to stage 1 when destroyInstances is called.
156 // In general, you don't need to worry about any of the above; just
157 // ensure registrationComplete() is called near the top of your main()
158 // function, otherwise no singletons can be instantiated.
160 class SingletonVault;
164 struct DefaultTag {};
166 // A TypeDescriptor is the unique handle for a given singleton. It is
167 // a combinaiton of the type and of the optional name, and is used as
168 // a key in unordered_maps.
169 class TypeDescriptor {
171 TypeDescriptor(const std::type_info& ti,
172 const std::type_info& tag_ti)
173 : ti_(ti), tag_ti_(tag_ti) {
176 TypeDescriptor(const TypeDescriptor& other)
177 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
180 TypeDescriptor& operator=(const TypeDescriptor& other) {
181 if (this != &other) {
183 tag_ti_ = other.tag_ti_;
189 std::string name() const {
190 auto ret = demangle(ti_.name());
191 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
193 ret += demangle(tag_ti_.name());
195 return ret.toStdString();
198 friend class TypeDescriptorHasher;
200 bool operator==(const TypeDescriptor& other) const {
201 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
206 std::type_index tag_ti_;
209 class TypeDescriptorHasher {
211 size_t operator()(const TypeDescriptor& ti) const {
212 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
216 // This interface is used by SingletonVault to interact with SingletonHolders.
217 // Having a non-template interface allows SingletonVault to keep a list of all
219 class SingletonHolderBase {
221 virtual ~SingletonHolderBase() = default;
223 virtual TypeDescriptor type() = 0;
224 virtual bool hasLiveInstance() = 0;
225 virtual void createInstance() = 0;
226 virtual bool creationStarted() = 0;
227 virtual void destroyInstance() = 0;
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();
244 inline std::shared_ptr<T> try_get();
245 inline folly::ReadMostlySharedPtr<T> try_get_fast();
247 void registerSingleton(CreateFunc c, TeardownFunc t);
248 void registerSingletonMock(CreateFunc c, TeardownFunc t);
249 virtual TypeDescriptor type() override;
250 virtual bool hasLiveInstance() override;
251 virtual void createInstance() override;
252 virtual bool creationStarted() override;
253 virtual void destroyInstance() override;
256 SingletonHolder(TypeDescriptor type, SingletonVault& vault);
258 enum class SingletonHolderState {
264 TypeDescriptor type_;
265 SingletonVault& vault_;
267 // mutex protects the entire entry during construction/destruction
270 // State of the singleton entry. If state is Living, instance_ptr and
271 // instance_weak can be safely accessed w/o synchronization.
272 std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
274 // the thread creating the singleton (only valid while creating an object)
275 std::atomic<std::thread::id> creating_thread_;
277 // The singleton itself and related functions.
279 // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
280 // from Dead to Living. Reset when state is changed from Living to Dead.
281 folly::ReadMostlyMainPtr<T> instance_;
282 // weak_ptr to the singleton instance, set when state is changed from Dead
283 // to Living. We never write to this object after initialization, so it is
284 // safe to read it from different threads w/o synchronization if we know
285 // that state is set to Living
286 std::weak_ptr<T> instance_weak_;
287 // Fast equivalent of instance_weak_
288 folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
289 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
290 std::shared_ptr<folly::Baton<>> destroy_baton_;
291 T* instance_ptr_ = nullptr;
292 CreateFunc create_ = nullptr;
293 TeardownFunc teardown_ = nullptr;
295 std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
297 SingletonHolder(const SingletonHolder&) = delete;
298 SingletonHolder& operator=(const SingletonHolder&) = delete;
299 SingletonHolder& operator=(SingletonHolder&&) = delete;
300 SingletonHolder(SingletonHolder&&) = delete;
305 class SingletonVault {
308 Strict, // Singletons can't be created before registrationComplete()
309 Relaxed, // Singletons can be created before registrationComplete()
313 * Clears all singletons in the given vault at ctor and dtor times.
314 * Useful for unit-tests that need to clear the world.
316 * This need can arise when a unit-test needs to swap out an object used by a
317 * singleton for a test-double, but the singleton needing its dependency to be
318 * swapped has a type or a tag local to some other translation unit and
319 * unavailable in the current translation unit.
321 * Other, better approaches to this need are "plz 2 refactor" ....
323 struct ScopedExpunger {
324 SingletonVault* vault;
325 explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
326 ~ScopedExpunger() { expunge(); }
328 vault->destroyInstances();
329 vault->reenableInstances();
333 explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
335 // Destructor is only called by unit tests to check destroyInstances.
338 typedef std::function<void(void*)> TeardownFunc;
339 typedef std::function<void*(void)> CreateFunc;
341 // Ensure that Singleton has not been registered previously and that
342 // registration is not complete. If validations succeeds,
343 // register a singleton of a given type with the create and teardown
345 void registerSingleton(detail::SingletonHolderBase* entry);
348 * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
349 * is built when `doEagerInit[Via]` is called; see those methods
352 void addEagerInitSingleton(detail::SingletonHolderBase* entry);
354 // Mark registration is complete; no more singletons can be
355 // registered at this point.
356 void registrationComplete();
359 * Initialize all singletons which were marked as eager-initialized
360 * (using `shouldEagerInit()`). No return value. Propagates exceptions
361 * from constructors / create functions, as is the usual case when calling
362 * for example `Singleton<Foo>::get_weak()`.
367 * Schedule eager singletons' initializations through the given executor.
368 * If baton ptr is not null, its `post` method is called after all
369 * early initialization has completed.
371 * If exceptions are thrown during initialization, this method will still
372 * `post` the baton to indicate completion. The exception will not propagate
373 * and future attempts to `try_get` or `get_weak` the failed singleton will
374 * retry initialization.
378 * wangle::IOThreadPoolExecutor executor(max_concurrency_level);
379 * folly::Baton<> done;
380 * doEagerInitVia(executor, &done);
381 * done.wait(); // or 'timed_wait', or spin with 'try_wait'
384 void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
386 // Destroy all singletons; when complete, the vault can't create
387 // singletons once again until reenableInstances() is called.
388 void destroyInstances();
390 // Enable re-creating singletons after destroyInstances() was called.
391 void reenableInstances();
393 // For testing; how many registered and living singletons we have.
394 size_t registeredSingletonCount() const {
395 RWSpinLock::ReadHolder rh(&mutex_);
397 return singletons_.size();
401 * Flips to true if eager initialization was used, and has completed.
402 * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
404 bool eagerInitComplete() const;
406 size_t livingSingletonCount() const {
407 RWSpinLock::ReadHolder rh(&mutex_);
410 for (const auto& p : singletons_) {
411 if (p.second->hasLiveInstance()) {
419 // A well-known vault; you can actually have others, but this is the
421 static SingletonVault* singleton() {
422 return singleton<>();
425 // Gets singleton vault for any Tag. Non-default tag should be used in unit
427 template <typename VaultTag = detail::DefaultTag>
428 static SingletonVault* singleton() {
429 static SingletonVault* vault =
430 detail::createGlobal<SingletonVault, VaultTag>();
434 typedef std::string(*StackTraceGetterPtr)();
436 static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
437 static std::atomic<StackTraceGetterPtr>* stackTraceGetterPtr =
438 detail::createGlobal<std::atomic<StackTraceGetterPtr>,
440 return *stackTraceGetterPtr;
444 template <typename T>
445 friend struct detail::SingletonHolder;
447 // The two stages of life for a vault, as mentioned in the class comment.
448 enum class SingletonVaultState {
453 // Each singleton in the vault can be in two states: dead
454 // (registered but never created), living (CreateFunc returned an instance).
456 void stateCheck(SingletonVaultState expected,
457 const char* msg="Unexpected singleton state change") {
458 if (expected != state_) {
459 throw std::logic_error(msg);
463 // This method only matters if registrationComplete() is never called.
464 // Otherwise destroyInstances is scheduled to be executed atexit.
466 // Initializes static object, which calls destroyInstances on destruction.
467 // Used to have better deletion ordering with singleton not managed by
468 // folly::Singleton. The desruction will happen in the following order:
469 // 1. Singletons, not managed by folly::Singleton, which were created after
470 // any of the singletons managed by folly::Singleton was requested.
471 // 2. All singletons managed by folly::Singleton
472 // 3. Singletons, not managed by folly::Singleton, which were created before
473 // any of the singletons managed by folly::Singleton was requested.
474 static void scheduleDestroyInstances();
476 typedef std::unordered_map<detail::TypeDescriptor,
477 detail::SingletonHolderBase*,
478 detail::TypeDescriptorHasher> SingletonMap;
480 mutable folly::RWSpinLock mutex_;
481 SingletonMap singletons_;
482 std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
483 std::vector<detail::TypeDescriptor> creation_order_;
484 SingletonVaultState state_{SingletonVaultState::Running};
485 bool registrationComplete_{false};
486 folly::RWSpinLock stateMutex_;
487 Type type_{Type::Relaxed};
490 // This is the wrapper class that most users actually interact with.
491 // It allows for simple access to registering and instantiating
492 // singletons. Create instances of this class in the global scope of
493 // type Singleton<T> to register your singleton for later access via
494 // Singleton<T>::try_get().
495 template <typename T,
496 typename Tag = detail::DefaultTag,
497 typename VaultTag = detail::DefaultTag /* for testing */>
500 typedef std::function<T*(void)> CreateFunc;
501 typedef std::function<void(T*)> TeardownFunc;
503 // Generally your program life cycle should be fine with calling
504 // get() repeatedly rather than saving the reference, and then not
505 // call get() during process shutdown.
506 FOLLY_DEPRECATED("Replaced by try_get")
507 static T* get() { return getEntry().get(); }
509 // If, however, you do need to hold a reference to the specific
510 // singleton, you can try to do so with a weak_ptr. Avoid this when
511 // possible but the inability to lock the weak pointer can be a
512 // signal that the vault has been destroyed.
513 FOLLY_DEPRECATED("Replaced by try_get")
514 static std::weak_ptr<T> get_weak() { return getEntry().get_weak(); }
516 // Preferred alternative to get_weak, it returns shared_ptr that can be
517 // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
518 // Avoid holding these shared_ptrs beyond the scope of a function;
519 // don't put them in member variables, always use try_get() instead
521 // try_get() can return nullptr if the singleton was destroyed, caller is
522 // responsible for handling nullptr return
523 static std::shared_ptr<T> try_get() {
524 return getEntry().try_get();
527 static folly::ReadMostlySharedPtr<T> try_get_fast() {
528 return getEntry().try_get_fast();
531 explicit Singleton(std::nullptr_t /* _ */ = nullptr,
532 typename Singleton::TeardownFunc t = nullptr)
533 : Singleton([]() { return new T; }, std::move(t)) {}
535 explicit Singleton(typename Singleton::CreateFunc c,
536 typename Singleton::TeardownFunc t = nullptr) {
538 throw std::logic_error(
539 "nullptr_t should be passed if you want T to be default constructed");
542 auto vault = SingletonVault::singleton<VaultTag>();
543 getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
544 vault->registerSingleton(&getEntry());
548 * Should be instantiated as soon as "doEagerInit[Via]" is called.
549 * Singletons are usually lazy-loaded (built on-demand) but for those which
550 * are known to be needed, to avoid the potential lag for objects that take
551 * long to construct during runtime, there is an option to make sure these
552 * are built up-front.
555 * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
557 * Or alternately, define the singleton as usual, and say
558 * gFooInstance.shouldEagerInit();
560 * at some point prior to calling registrationComplete().
561 * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
563 Singleton& shouldEagerInit() {
564 auto vault = SingletonVault::singleton<VaultTag>();
565 vault->addEagerInitSingleton(&getEntry());
570 * Construct and inject a mock singleton which should be used only from tests.
571 * Unlike regular singletons which are initialized once per process lifetime,
572 * mock singletons live for the duration of a test. This means that one process
573 * running multiple tests can initialize and register the same singleton
574 * multiple times. This functionality should be used only from tests
575 * since it relaxes validation and performance in order to be able to perform
576 * the injection. The returned mock singleton is functionality identical to
577 * regular singletons.
579 static void make_mock(std::nullptr_t /* c */ = nullptr,
580 typename Singleton<T>::TeardownFunc t = nullptr) {
581 make_mock([]() { return new T; }, t);
584 static void make_mock(CreateFunc c,
585 typename Singleton<T>::TeardownFunc t = nullptr) {
587 throw std::logic_error(
588 "nullptr_t should be passed if you want T to be default constructed");
591 auto& entry = getEntry();
593 entry.registerSingletonMock(c, getTeardownFunc(t));
597 inline static detail::SingletonHolder<T>& getEntry() {
598 return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
601 // Construct TeardownFunc.
602 static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
605 return [](T* v) { delete v; };
612 template <typename T, typename Tag = detail::DefaultTag>
613 class LeakySingleton {
615 using CreateFunc = std::function<T*()>;
617 LeakySingleton() : LeakySingleton([] { return new T(); }) {}
619 explicit LeakySingleton(CreateFunc createFunc) {
620 auto& entry = entryInstance();
621 if (entry.state != State::NotRegistered) {
622 LOG(FATAL) << "Double registration of singletons of the same "
623 << "underlying type; check for multiple definitions "
624 << "of type folly::LeakySingleton<" + entry.type_.name() + ">";
626 entry.createFunc = createFunc;
627 entry.state = State::Dead;
630 static T& get() { return instance(); }
633 enum class State { NotRegistered, Dead, Living };
637 Entry(const Entry&) = delete;
638 Entry& operator=(const Entry&) = delete;
640 std::atomic<State> state{State::NotRegistered};
642 CreateFunc createFunc;
644 detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
647 static Entry& entryInstance() {
648 static auto entry = detail::createGlobal<Entry, Tag>();
652 static T& instance() {
653 auto& entry = entryInstance();
654 if (UNLIKELY(entry.state != State::Living)) {
661 static void createInstance() {
662 auto& entry = entryInstance();
664 std::lock_guard<std::mutex> lg(entry.mutex);
665 if (entry.state == State::Living) {
669 if (entry.state == State::NotRegistered) {
670 auto ptr = SingletonVault::stackTraceGetter().load();
671 LOG(FATAL) << "Creating instance for unregistered singleton: "
672 << entry.type_.name() << "\n"
674 << "\n" << (ptr ? (*ptr)() : "(not available)");
677 entry.ptr = entry.createFunc();
678 entry.state = State::Living;
683 #include <folly/Singleton-inl.h>