2 * Copyright 2017 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 // Recommended usage of this class: 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 {
26 // // Caution - may return a null ptr during startup and shutdown.
27 // static std::shared_ptr<MyExpensiveService> getInstance();
32 // namespace { struct PrivateTag {}; }
33 // static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton;
34 // std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() {
35 // return the_singleton.try_get();
38 // Code in other modules can access it via:
40 // auto instance = MyExpensiveService::getInstance();
42 // Advanced usage and notes:
44 // You can also access a singleton instance with
45 // `Singleton<ObjectType, TagType>::try_get()`. We recommend
46 // that you prefer the form `the_singleton.try_get()` because it ensures that
47 // `the_singleton` is used and cannot be garbage-collected during linking: this
48 // is necessary because the constructor of `the_singleton` is what registers it
49 // to the SingletonVault.
51 // The singleton will be created on demand. If the constructor for
52 // MyExpensiveService actually makes use of *another* Singleton, then
53 // the right thing will happen -- that other singleton will complete
54 // construction before get() returns. However, in the event of a
55 // circular dependency, a runtime error will occur.
57 // You can have multiple singletons of the same underlying type, but
58 // each must be given a unique tag. If no tag is specified a default tag is
59 // used. We recommend that you use a tag from an anonymous namespace private to
60 // your implementation file, as this ensures that the singleton is only
61 // available via your interface and not also through Singleton<T>::try_get()
66 // folly::Singleton<MyExpensiveService> s_default;
67 // folly::Singleton<MyExpensiveService, Tag1> s1;
68 // folly::Singleton<MyExpensiveService, Tag2> s2;
71 // MyExpensiveService* svc_default = s_default.get();
72 // MyExpensiveService* svc1 = s1.get();
73 // MyExpensiveService* svc2 = s2.get();
75 // By default, the singleton instance is constructed via new and
76 // deleted via delete, but this is configurable:
78 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
81 // Where create and destroy are functions, Singleton<T>::CreateFunc
82 // Singleton<T>::TeardownFunc.
84 // For example, if you need to pass arguments to your class's constructor:
87 // X(int a1, std::string a2);
90 // Make your singleton like this:
91 // folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); });
93 // The above examples detail a situation where an expensive singleton is loaded
94 // on-demand (thus only if needed). However if there is an expensive singleton
95 // that will likely be needed, and initialization takes a potentially long time,
96 // e.g. while initializing, parsing some files, talking to remote services,
97 // making uses of other singletons, and so on, the initialization of those can
98 // be scheduled up front, or "eagerly".
100 // In that case the singleton can be declared this way:
103 // auto the_singleton =
104 // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
105 // .shouldEagerInit();
108 // This way the singleton's instance is built at program initialization,
109 // if the program opted-in to that feature by calling "doEagerInit" or
110 // "doEagerInitVia" during its startup.
112 // What if you need to destroy all of your singletons? Say, some of
113 // your singletons manage threads, but you need to fork? Or your unit
114 // test wants to clean up all global state? Then you can call
115 // SingletonVault::singleton()->destroyInstances(), which invokes the
116 // TeardownFunc for each singleton, in the reverse order they were
117 // created. It is your responsibility to ensure your singletons can
118 // handle cases where the singletons they depend on go away, however.
119 // Singletons won't be recreated after destroyInstances call. If you
120 // want to re-enable singleton creation (say after fork was called) you
121 // should call reenableInstances.
124 #include <folly/Baton.h>
125 #include <folly/Demangle.h>
126 #include <folly/Exception.h>
127 #include <folly/Executor.h>
128 #include <folly/Hash.h>
129 #include <folly/Memory.h>
130 #include <folly/RWSpinLock.h>
131 #include <folly/Synchronized.h>
132 #include <folly/detail/StaticSingletonManager.h>
133 #include <folly/experimental/ReadMostlySharedPtr.h>
137 #include <condition_variable>
138 #include <functional>
145 #include <unordered_map>
146 #include <unordered_set>
149 #include <glog/logging.h>
151 // use this guard to handleSingleton breaking change in 3rd party code
152 #ifndef FOLLY_SINGLETON_TRY_GET
153 #define FOLLY_SINGLETON_TRY_GET
158 // For actual usage, please see the Singleton<T> class at the bottom
159 // of this file; that is what you will actually interact with.
161 // SingletonVault is the class that manages singleton instances. It
162 // is unaware of the underlying types of singletons, and simply
163 // manages lifecycles and invokes CreateFunc and TeardownFunc when
164 // appropriate. In general, you won't need to interact with the
165 // SingletonVault itself.
167 // A vault goes through a few stages of life:
169 // 1. Registration phase; singletons can be registered:
170 // a) Strict: no singleton can be created in this stage.
171 // b) Relaxed: singleton can be created (the default vault is Relaxed).
172 // 2. registrationComplete() has been called; singletons can no
173 // longer be registered, but they can be created.
174 // 3. A vault can return to stage 1 when destroyInstances is called.
176 // In general, you don't need to worry about any of the above; just
177 // ensure registrationComplete() is called near the top of your main()
178 // function, otherwise no singletons can be instantiated.
180 class SingletonVault;
184 struct DefaultTag {};
186 // A TypeDescriptor is the unique handle for a given singleton. It is
187 // a combinaiton of the type and of the optional name, and is used as
188 // a key in unordered_maps.
189 class TypeDescriptor {
191 TypeDescriptor(const std::type_info& ti,
192 const std::type_info& tag_ti)
193 : ti_(ti), tag_ti_(tag_ti) {
196 TypeDescriptor(const TypeDescriptor& other)
197 : ti_(other.ti_), tag_ti_(other.tag_ti_) {
200 TypeDescriptor& operator=(const TypeDescriptor& other) {
201 if (this != &other) {
203 tag_ti_ = other.tag_ti_;
209 std::string name() const {
210 auto ret = demangle(ti_.name());
211 if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
213 ret += demangle(tag_ti_.name());
215 return ret.toStdString();
218 friend class TypeDescriptorHasher;
220 bool operator==(const TypeDescriptor& other) const {
221 return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
226 std::type_index tag_ti_;
229 class TypeDescriptorHasher {
231 size_t operator()(const TypeDescriptor& ti) const {
232 return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
236 // This interface is used by SingletonVault to interact with SingletonHolders.
237 // Having a non-template interface allows SingletonVault to keep a list of all
239 class SingletonHolderBase {
241 explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {}
242 virtual ~SingletonHolderBase() = default;
244 TypeDescriptor type() const {
247 virtual bool hasLiveInstance() = 0;
248 virtual void createInstance() = 0;
249 virtual bool creationStarted() = 0;
250 virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0;
251 virtual void destroyInstance() = 0;
254 TypeDescriptor type_;
257 // An actual instance of a singleton, tracking the instance itself,
258 // its state as described above, and the create and teardown
260 template <typename T>
261 struct SingletonHolder : public SingletonHolderBase {
263 typedef std::function<void(T*)> TeardownFunc;
264 typedef std::function<T*(void)> CreateFunc;
266 template <typename Tag, typename VaultTag>
267 inline static SingletonHolder<T>& singleton();
270 inline std::weak_ptr<T> get_weak();
271 inline std::shared_ptr<T> try_get();
272 inline folly::ReadMostlySharedPtr<T> try_get_fast();
274 void registerSingleton(CreateFunc c, TeardownFunc t);
275 void registerSingletonMock(CreateFunc c, TeardownFunc t);
276 virtual bool hasLiveInstance() override;
277 virtual void createInstance() override;
278 virtual bool creationStarted() override;
279 virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override;
280 virtual void destroyInstance() override;
283 SingletonHolder(TypeDescriptor type, SingletonVault& vault);
285 enum class SingletonHolderState {
291 SingletonVault& vault_;
293 // mutex protects the entire entry during construction/destruction
296 // State of the singleton entry. If state is Living, instance_ptr and
297 // instance_weak can be safely accessed w/o synchronization.
298 std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
300 // the thread creating the singleton (only valid while creating an object)
301 std::atomic<std::thread::id> creating_thread_;
303 // The singleton itself and related functions.
305 // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
306 // from Dead to Living. Reset when state is changed from Living to Dead.
307 folly::ReadMostlyMainPtr<T> instance_;
308 // used to release all ReadMostlyMainPtrs at once
309 folly::ReadMostlySharedPtr<T> instance_copy_;
310 // weak_ptr to the singleton instance, set when state is changed from Dead
311 // to Living. We never write to this object after initialization, so it is
312 // safe to read it from different threads w/o synchronization if we know
313 // that state is set to Living
314 std::weak_ptr<T> instance_weak_;
315 // Fast equivalent of instance_weak_
316 folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
317 // Time we wait on destroy_baton after releasing Singleton shared_ptr.
318 std::shared_ptr<folly::Baton<>> destroy_baton_;
319 T* instance_ptr_ = nullptr;
320 CreateFunc create_ = nullptr;
321 TeardownFunc teardown_ = nullptr;
323 std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
325 SingletonHolder(const SingletonHolder&) = delete;
326 SingletonHolder& operator=(const SingletonHolder&) = delete;
327 SingletonHolder& operator=(SingletonHolder&&) = delete;
328 SingletonHolder(SingletonHolder&&) = delete;
333 class SingletonVault {
336 Strict, // Singletons can't be created before registrationComplete()
337 Relaxed, // Singletons can be created before registrationComplete()
341 * Clears all singletons in the given vault at ctor and dtor times.
342 * Useful for unit-tests that need to clear the world.
344 * This need can arise when a unit-test needs to swap out an object used by a
345 * singleton for a test-double, but the singleton needing its dependency to be
346 * swapped has a type or a tag local to some other translation unit and
347 * unavailable in the current translation unit.
349 * Other, better approaches to this need are "plz 2 refactor" ....
351 struct ScopedExpunger {
352 SingletonVault* vault;
353 explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
354 ~ScopedExpunger() { expunge(); }
356 vault->destroyInstances();
357 vault->reenableInstances();
361 explicit SingletonVault(Type type = Type::Strict) : type_(type) {}
363 // Destructor is only called by unit tests to check destroyInstances.
366 typedef std::function<void(void*)> TeardownFunc;
367 typedef std::function<void*(void)> CreateFunc;
369 // Ensure that Singleton has not been registered previously and that
370 // registration is not complete. If validations succeeds,
371 // register a singleton of a given type with the create and teardown
373 void registerSingleton(detail::SingletonHolderBase* entry);
376 * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
377 * is built when `doEagerInit[Via]` is called; see those methods
380 void addEagerInitSingleton(detail::SingletonHolderBase* entry);
382 // Mark registration is complete; no more singletons can be
383 // registered at this point.
384 void registrationComplete();
387 * Initialize all singletons which were marked as eager-initialized
388 * (using `shouldEagerInit()`). No return value. Propagates exceptions
389 * from constructors / create functions, as is the usual case when calling
390 * for example `Singleton<Foo>::get_weak()`.
395 * Schedule eager singletons' initializations through the given executor.
396 * If baton ptr is not null, its `post` method is called after all
397 * early initialization has completed.
399 * If exceptions are thrown during initialization, this method will still
400 * `post` the baton to indicate completion. The exception will not propagate
401 * and future attempts to `try_get` or `get_weak` the failed singleton will
402 * retry initialization.
406 * wangle::IOThreadPoolExecutor executor(max_concurrency_level);
407 * folly::Baton<> done;
408 * doEagerInitVia(executor, &done);
409 * done.wait(); // or 'timed_wait', or spin with 'try_wait'
412 void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
414 // Destroy all singletons; when complete, the vault can't create
415 // singletons once again until reenableInstances() is called.
416 void destroyInstances();
418 // Enable re-creating singletons after destroyInstances() was called.
419 void reenableInstances();
421 // For testing; how many registered and living singletons we have.
422 size_t registeredSingletonCount() const {
423 return singletons_.rlock()->size();
427 * Flips to true if eager initialization was used, and has completed.
428 * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
430 bool eagerInitComplete() const;
432 size_t livingSingletonCount() const {
433 auto singletons = singletons_.rlock();
436 for (const auto& p : *singletons) {
437 if (p.second->hasLiveInstance()) {
445 // A well-known vault; you can actually have others, but this is the
447 static SingletonVault* singleton() {
448 return singleton<>();
451 // Gets singleton vault for any Tag. Non-default tag should be used in unit
453 template <typename VaultTag = detail::DefaultTag>
454 static SingletonVault* singleton() {
455 /* library-local */ static auto vault =
456 detail::createGlobal<SingletonVault, VaultTag>();
460 typedef std::string(*StackTraceGetterPtr)();
462 static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
463 /* library-local */ static auto stackTraceGetterPtr = detail::
464 createGlobal<std::atomic<StackTraceGetterPtr>, SingletonVault>();
465 return *stackTraceGetterPtr;
468 void setType(Type type) {
473 template <typename T>
474 friend struct detail::SingletonHolder;
476 // The two stages of life for a vault, as mentioned in the class comment.
477 enum class SingletonVaultState {
483 SingletonVaultState state{SingletonVaultState::Running};
484 bool registrationComplete{false};
487 // Each singleton in the vault can be in two states: dead
488 // (registered but never created), living (CreateFunc returned an instance).
490 static void stateCheck(
491 SingletonVaultState expected,
493 const char* msg = "Unexpected singleton state change") {
494 if (expected != state.state) {
495 throw std::logic_error(msg);
499 // This method only matters if registrationComplete() is never called.
500 // Otherwise destroyInstances is scheduled to be executed atexit.
502 // Initializes static object, which calls destroyInstances on destruction.
503 // Used to have better deletion ordering with singleton not managed by
504 // folly::Singleton. The desruction will happen in the following order:
505 // 1. Singletons, not managed by folly::Singleton, which were created after
506 // any of the singletons managed by folly::Singleton was requested.
507 // 2. All singletons managed by folly::Singleton
508 // 3. Singletons, not managed by folly::Singleton, which were created before
509 // any of the singletons managed by folly::Singleton was requested.
510 static void scheduleDestroyInstances();
512 typedef std::unordered_map<detail::TypeDescriptor,
513 detail::SingletonHolderBase*,
514 detail::TypeDescriptorHasher> SingletonMap;
515 folly::Synchronized<SingletonMap> singletons_;
516 folly::Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
517 eagerInitSingletons_;
518 folly::Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
520 // Using SharedMutexReadPriority is important here, because we want to make
521 // sure we don't block nested singleton creation happening concurrently with
522 // destroyInstances().
523 folly::Synchronized<State, folly::SharedMutexReadPriority> state_;
528 // This is the wrapper class that most users actually interact with.
529 // It allows for simple access to registering and instantiating
530 // singletons. Create instances of this class in the global scope of
531 // type Singleton<T> to register your singleton for later access via
532 // Singleton<T>::try_get().
533 template <typename T,
534 typename Tag = detail::DefaultTag,
535 typename VaultTag = detail::DefaultTag /* for testing */>
538 typedef std::function<T*(void)> CreateFunc;
539 typedef std::function<void(T*)> TeardownFunc;
541 // Generally your program life cycle should be fine with calling
542 // get() repeatedly rather than saving the reference, and then not
543 // call get() during process shutdown.
544 FOLLY_DEPRECATED("Replaced by try_get")
545 static T* get() { return getEntry().get(); }
547 // If, however, you do need to hold a reference to the specific
548 // singleton, you can try to do so with a weak_ptr. Avoid this when
549 // possible but the inability to lock the weak pointer can be a
550 // signal that the vault has been destroyed.
551 FOLLY_DEPRECATED("Replaced by try_get")
552 static std::weak_ptr<T> get_weak() { 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
559 // try_get() can return nullptr if the singleton was destroyed, caller is
560 // responsible for handling nullptr return
561 static std::shared_ptr<T> try_get() {
562 return getEntry().try_get();
565 static folly::ReadMostlySharedPtr<T> try_get_fast() {
566 return getEntry().try_get_fast();
569 explicit Singleton(std::nullptr_t /* _ */ = nullptr,
570 typename Singleton::TeardownFunc t = nullptr)
571 : Singleton([]() { return new T; }, std::move(t)) {}
573 explicit Singleton(typename Singleton::CreateFunc c,
574 typename Singleton::TeardownFunc t = nullptr) {
576 throw std::logic_error(
577 "nullptr_t should be passed if you want T to be default constructed");
580 auto vault = SingletonVault::singleton<VaultTag>();
581 getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
582 vault->registerSingleton(&getEntry());
586 * Should be instantiated as soon as "doEagerInit[Via]" is called.
587 * Singletons are usually lazy-loaded (built on-demand) but for those which
588 * are known to be needed, to avoid the potential lag for objects that take
589 * long to construct during runtime, there is an option to make sure these
590 * are built up-front.
593 * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
595 * Or alternately, define the singleton as usual, and say
596 * gFooInstance.shouldEagerInit();
598 * at some point prior to calling registrationComplete().
599 * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
601 Singleton& shouldEagerInit() {
602 auto vault = SingletonVault::singleton<VaultTag>();
603 vault->addEagerInitSingleton(&getEntry());
608 * Construct and inject a mock singleton which should be used only from tests.
609 * Unlike regular singletons which are initialized once per process lifetime,
610 * mock singletons live for the duration of a test. This means that one process
611 * running multiple tests can initialize and register the same singleton
612 * multiple times. This functionality should be used only from tests
613 * since it relaxes validation and performance in order to be able to perform
614 * the injection. The returned mock singleton is functionality identical to
615 * regular singletons.
617 static void make_mock(std::nullptr_t /* c */ = nullptr,
618 typename Singleton<T>::TeardownFunc t = nullptr) {
619 make_mock([]() { return new T; }, t);
622 static void make_mock(CreateFunc c,
623 typename Singleton<T>::TeardownFunc t = nullptr) {
625 throw std::logic_error(
626 "nullptr_t should be passed if you want T to be default constructed");
629 auto& entry = getEntry();
631 entry.registerSingletonMock(c, getTeardownFunc(t));
635 inline static detail::SingletonHolder<T>& getEntry() {
636 return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
639 // Construct TeardownFunc.
640 static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
643 return [](T* v) { delete v; };
650 template <typename T, typename Tag = detail::DefaultTag>
651 class LeakySingleton {
653 using CreateFunc = std::function<T*()>;
655 LeakySingleton() : LeakySingleton([] { return new T(); }) {}
657 explicit LeakySingleton(CreateFunc createFunc) {
658 auto& entry = entryInstance();
659 if (entry.state != State::NotRegistered) {
660 LOG(FATAL) << "Double registration of singletons of the same "
661 << "underlying type; check for multiple definitions "
662 << "of type folly::LeakySingleton<" + entry.type_.name() + ">";
664 entry.createFunc = createFunc;
665 entry.state = State::Dead;
668 static T& get() { return instance(); }
671 enum class State { NotRegistered, Dead, Living };
675 Entry(const Entry&) = delete;
676 Entry& operator=(const Entry&) = delete;
678 std::atomic<State> state{State::NotRegistered};
680 CreateFunc createFunc;
682 detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
685 static Entry& entryInstance() {
686 /* library-local */ static auto entry = detail::createGlobal<Entry, Tag>();
690 static T& instance() {
691 auto& entry = entryInstance();
692 if (UNLIKELY(entry.state != State::Living)) {
699 static void createInstance() {
700 auto& entry = entryInstance();
702 std::lock_guard<std::mutex> lg(entry.mutex);
703 if (entry.state == State::Living) {
707 if (entry.state == State::NotRegistered) {
708 auto ptr = SingletonVault::stackTraceGetter().load();
709 LOG(FATAL) << "Creating instance for unregistered singleton: "
710 << entry.type_.name() << "\n"
712 << "\n" << (ptr ? (*ptr)() : "(not available)");
715 entry.ptr = entry.createFunc();
716 entry.state = State::Living;
721 #include <folly/Singleton-inl.h>