X-Git-Url: http://plrg.eecs.uci.edu/git/?a=blobdiff_plain;f=folly%2FSingleton.h;h=c5fe79db274c0d15ebcbebf3a7efea282229e2ff;hb=95e7a3bad41357c9f78d0a993b542b002f17e00e;hp=ac5b8328d3e28bda1868682c35482a82d72f4465;hpb=f54fbf88038aacc4bcc0f3bf98995375fddcde78;p=folly.git diff --git a/folly/Singleton.h b/folly/Singleton.h index ac5b8328..c5fe79db 100644 --- a/folly/Singleton.h +++ b/folly/Singleton.h @@ -1,5 +1,5 @@ /* - * Copyright 2015 Facebook, Inc. + * Copyright 2016 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,19 +109,22 @@ #include #include #include -#include +#include +#include #include -#include -#include -#include +#include #include +#include +#include +#include #include +#include +#include +#include #include #include -#include -#include -#include +#include #include @@ -241,6 +244,8 @@ struct SingletonHolder : public SingletonHolderBase { inline T* get(); inline std::weak_ptr get_weak(); + inline std::shared_ptr try_get(); + inline folly::ReadMostlySharedPtr try_get_fast(); void registerSingleton(CreateFunc c, TeardownFunc t); void registerSingletonMock(CreateFunc c, TeardownFunc t); @@ -274,14 +279,16 @@ struct SingletonHolder : public SingletonHolderBase { // The singleton itself and related functions. - // holds a shared_ptr to singleton instance, set when state is changed from - // Dead to Living. Reset when state is changed from Living to Dead. - std::shared_ptr instance_; + // holds a ReadMostlyMainPtr to singleton instance, set when state is changed + // from Dead to Living. Reset when state is changed from Living to Dead. + folly::ReadMostlyMainPtr instance_; // weak_ptr to the singleton instance, set when state is changed from Dead // to Living. We never write to this object after initialization, so it is // safe to read it from different threads w/o synchronization if we know // that state is set to Living std::weak_ptr instance_weak_; + // Fast equivalent of instance_weak_ + folly::ReadMostlyWeakPtr instance_weak_fast_; // Time we wait on destroy_baton after releasing Singleton shared_ptr. std::shared_ptr> destroy_baton_; T* instance_ptr_ = nullptr; @@ -305,6 +312,27 @@ class SingletonVault { Relaxed, // Singletons can be created before registrationComplete() }; + /** + * Clears all singletons in the given vault at ctor and dtor times. + * Useful for unit-tests that need to clear the world. + * + * This need can arise when a unit-test needs to swap out an object used by a + * singleton for a test-double, but the singleton needing its dependency to be + * swapped has a type or a tag local to some other translation unit and + * unavailable in the current translation unit. + * + * Other, better approaches to this need are "plz 2 refactor" .... + */ + struct ScopedExpunger { + SingletonVault* vault; + explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); } + ~ScopedExpunger() { expunge(); } + void expunge() { + vault->destroyInstances(); + vault->reenableInstances(); + } + }; + explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {} // Destructor is only called by unit tests to check destroyInstances. @@ -340,8 +368,23 @@ class SingletonVault { /** * Schedule eager singletons' initializations through the given executor. + * If baton ptr is not null, its `post` method is called after all + * early initialization has completed. + * + * If exceptions are thrown during initialization, this method will still + * `post` the baton to indicate completion. The exception will not propagate + * and future attempts to `try_get` or `get_weak` the failed singleton will + * retry initialization. + * + * Sample usage: + * + * wangle::IOThreadPoolExecutor executor(max_concurrency_level); + * folly::Baton<> done; + * doEagerInitVia(executor, &done); + * done.wait(); // or 'timed_wait', or spin with 'try_wait' + * */ - void doEagerInitVia(Executor* exe); + void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr); // Destroy all singletons; when complete, the vault can't create // singletons once again until reenableInstances() is called. @@ -357,6 +400,12 @@ class SingletonVault { return singletons_.size(); } + /** + * Flips to true if eager initialization was used, and has completed. + * Never set to true if "doEagerInit()" or "doEagerInitVia" never called. + */ + bool eagerInitComplete() const; + size_t livingSingletonCount() const { RWSpinLock::ReadHolder rh(&mutex_); @@ -380,15 +429,18 @@ class SingletonVault { // tests only. template static SingletonVault* singleton() { - static SingletonVault* vault = new SingletonVault(); + static SingletonVault* vault = + detail::createGlobal(); return vault; } typedef std::string(*StackTraceGetterPtr)(); static std::atomic& stackTraceGetter() { - static std::atomic stackTraceGetterPtr; - return stackTraceGetterPtr; + static std::atomic* stackTraceGetterPtr = + detail::createGlobal, + SingletonVault>(); + return *stackTraceGetterPtr; } private: @@ -454,38 +506,35 @@ class Singleton { // Generally your program life cycle should be fine with calling // get() repeatedly rather than saving the reference, and then not // call get() during process shutdown. - static T* get() __attribute__ ((__deprecated__("Replaced by try_get"))) { - return getEntry().get(); - } + FOLLY_DEPRECATED("Replaced by try_get") + static T* get() { return getEntry().get(); } // If, however, you do need to hold a reference to the specific // singleton, you can try to do so with a weak_ptr. Avoid this when // possible but the inability to lock the weak pointer can be a // signal that the vault has been destroyed. - static std::weak_ptr get_weak() { - return getEntry().get_weak(); - } + FOLLY_DEPRECATED("Replaced by try_get") + static std::weak_ptr get_weak() { return getEntry().get_weak(); } // Preferred alternative to get_weak, it returns shared_ptr that can be // stored; a singleton won't be destroyed unless shared_ptr is destroyed. // Avoid holding these shared_ptrs beyond the scope of a function; // don't put them in member variables, always use try_get() instead + // + // try_get() can return nullptr if the singleton was destroyed, caller is + // responsible for handling nullptr return static std::shared_ptr try_get() { - auto ret = get_weak().lock(); - if (!ret) { - LOG(DFATAL) << - "folly::Singleton<" << getEntry().type().name() << - ">::get_weak() called on destructed singleton; " - "returning nullptr, possible segfault coming"; - } - return ret; + return getEntry().try_get(); } - explicit Singleton(std::nullptr_t _ = nullptr, - typename Singleton::TeardownFunc t = nullptr) : - Singleton ([]() { return new T; }, std::move(t)) { + static folly::ReadMostlySharedPtr try_get_fast() { + return getEntry().try_get_fast(); } + explicit Singleton(std::nullptr_t /* _ */ = nullptr, + typename Singleton::TeardownFunc t = nullptr) + : Singleton([]() { return new T; }, std::move(t)) {} + explicit Singleton(typename Singleton::CreateFunc c, typename Singleton::TeardownFunc t = nullptr) { if (c == nullptr) { @@ -530,7 +579,7 @@ class Singleton { * the injection. The returned mock singleton is functionality identical to * regular singletons. */ - static void make_mock(std::nullptr_t c = nullptr, + static void make_mock(std::nullptr_t /* c */ = nullptr, typename Singleton::TeardownFunc t = nullptr) { make_mock([]() { return new T; }, t); } @@ -563,6 +612,75 @@ class Singleton { } }; +template +class LeakySingleton { + public: + using CreateFunc = std::function; + + LeakySingleton() : LeakySingleton([] { return new T(); }) {} + + explicit LeakySingleton(CreateFunc createFunc) { + auto& entry = entryInstance(); + if (entry.state != State::NotRegistered) { + LOG(FATAL) << "Double registration of singletons of the same " + << "underlying type; check for multiple definitions " + << "of type folly::LeakySingleton<" + entry.type_.name() + ">"; + } + entry.createFunc = createFunc; + entry.state = State::Dead; + } + + static T& get() { return instance(); } + + private: + enum class State { NotRegistered, Dead, Living }; + + struct Entry { + Entry() {} + Entry(const Entry&) = delete; + Entry& operator=(const Entry&) = delete; + + std::atomic state{State::NotRegistered}; + T* ptr{nullptr}; + CreateFunc createFunc; + std::mutex mutex; + detail::TypeDescriptor type_{typeid(T), typeid(Tag)}; + }; + + static Entry& entryInstance() { + static auto entry = detail::createGlobal(); + return *entry; + } + + static T& instance() { + auto& entry = entryInstance(); + if (UNLIKELY(entry.state != State::Living)) { + createInstance(); + } + + return *entry.ptr; + } + + static void createInstance() { + auto& entry = entryInstance(); + + std::lock_guard lg(entry.mutex); + if (entry.state == State::Living) { + return; + } + + if (entry.state == State::NotRegistered) { + auto ptr = SingletonVault::stackTraceGetter().load(); + LOG(FATAL) << "Creating instance for unregistered singleton: " + << entry.type_.name() << "\n" + << "Stacktrace:" + << "\n" << (ptr ? (*ptr)() : "(not available)"); + } + + entry.ptr = entry.createFunc(); + entry.state = State::Living; + } +}; } #include