X-Git-Url: http://plrg.eecs.uci.edu/git/?p=folly.git;a=blobdiff_plain;f=folly%2FSingleton.h;h=e8344cef55348bba3375de28b91e4b414f846ffd;hp=8f55a49a56153cc9d9bff78ca389641ae32acf4e;hb=24c892da36fc7d4f8cad6a3c94bdf6f1024d99c4;hpb=68a47850f7cd222e3664e82fc9da2b3c0e3b3d28 diff --git a/folly/Singleton.h b/folly/Singleton.h index 8f55a49a..e8344cef 100644 --- a/folly/Singleton.h +++ b/folly/Singleton.h @@ -1,5 +1,5 @@ /* - * Copyright 2015 Facebook, Inc. + * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,29 +17,36 @@ // SingletonVault - a library to manage the creation and destruction // of interdependent singletons. // -// Basic usage of this class is very simple; suppose you have a class +// Recommended usage of this class: suppose you have a class // called MyExpensiveService, and you only want to construct one (ie, // it's a singleton), but you only want to construct it if it is used. // // In your .h file: -// class MyExpensiveService { ... }; +// class MyExpensiveService { +// // Caution - may return a null ptr during startup and shutdown. +// static std::shared_ptr getInstance(); +// .... +// }; // // In your .cpp file: -// namespace { folly::Singleton the_singleton; } +// namespace { struct PrivateTag {}; } +// static folly::Singleton the_singleton; +// std::shared_ptr MyExpensiveService::getInstance() { +// return the_singleton.try_get(); +// } // -// Code can access it via: +// Code in other modules can access it via: // -// MyExpensiveService* instance = Singleton::get(); -// or -// std::weak_ptr instance = -// Singleton::get_weak(); +// auto instance = MyExpensiveService::getInstance(); // -// You also can directly access it by the variable defining the -// singleton rather than via get(), and even treat that variable like -// a smart pointer (dereferencing it or using the -> operator). +// Advanced usage and notes: // -// Please note, however, that all non-weak_ptr interfaces are -// inherently subject to races with destruction. Use responsibly. +// You can also access a singleton instance with +// `Singleton::try_get()`. We recommend +// that you prefer the form `the_singleton.try_get()` because it ensures that +// `the_singleton` is used and cannot be garbage-collected during linking: this +// is necessary because the constructor of `the_singleton` is what registers it +// to the SingletonVault. // // The singleton will be created on demand. If the constructor for // MyExpensiveService actually makes use of *another* Singleton, then @@ -48,7 +55,10 @@ // circular dependency, a runtime error will occur. // // You can have multiple singletons of the same underlying type, but -// each must be given a unique tag. If no tag is specified - default tag is used +// each must be given a unique tag. If no tag is specified a default tag is +// used. We recommend that you use a tag from an anonymous namespace private to +// your implementation file, as this ensures that the singleton is only +// available via your interface and not also through Singleton::try_get() // // namespace { // struct Tag1 {}; @@ -71,6 +81,15 @@ // Where create and destroy are functions, Singleton::CreateFunc // Singleton::TeardownFunc. // +// For example, if you need to pass arguments to your class's constructor: +// class X { +// public: +// X(int a1, std::string a2); +// // ... +// } +// Make your singleton like this: +// folly::Singleton singleton_x([]() { return new X(42, "foo"); }); +// // The above examples detail a situation where an expensive singleton is loaded // on-demand (thus only if needed). However if there is an expensive singleton // that will likely be needed, and initialization takes a potentially long time, @@ -103,13 +122,14 @@ #pragma once #include +#include #include +#include #include #include #include -#include -#include -#include +#include +#include #include #include @@ -218,16 +238,20 @@ class TypeDescriptorHasher { // SingletonHolders. class SingletonHolderBase { public: + explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {} virtual ~SingletonHolderBase() = default; - virtual TypeDescriptor type() = 0; + TypeDescriptor type() const { + return type_; + } virtual bool hasLiveInstance() = 0; virtual void createInstance() = 0; virtual bool creationStarted() = 0; + virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0; virtual void destroyInstance() = 0; - protected: - static constexpr std::chrono::seconds kDestroyWaitTime{5}; + private: + TypeDescriptor type_; }; // An actual instance of a singleton, tracking the instance itself, @@ -249,10 +273,10 @@ struct SingletonHolder : public SingletonHolderBase { void registerSingleton(CreateFunc c, TeardownFunc t); void registerSingletonMock(CreateFunc c, TeardownFunc t); - virtual TypeDescriptor type() override; virtual bool hasLiveInstance() override; virtual void createInstance() override; virtual bool creationStarted() override; + virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override; virtual void destroyInstance() override; private: @@ -264,7 +288,6 @@ struct SingletonHolder : public SingletonHolderBase { Living, }; - TypeDescriptor type_; SingletonVault& vault_; // mutex protects the entire entry during construction/destruction @@ -282,6 +305,8 @@ struct SingletonHolder : public SingletonHolderBase { // 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_; + // used to release all ReadMostlyMainPtrs at once + folly::ReadMostlySharedPtr instance_copy_; // 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 @@ -333,7 +358,9 @@ class SingletonVault { } }; - explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {} + static Type defaultVaultType(); + + explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {} // Destructor is only called by unit tests to check destroyInstances. ~SingletonVault(); @@ -395,9 +422,7 @@ class SingletonVault { // For testing; how many registered and living singletons we have. size_t registeredSingletonCount() const { - RWSpinLock::ReadHolder rh(&mutex_); - - return singletons_.size(); + return singletons_.rlock()->size(); } /** @@ -407,10 +432,10 @@ class SingletonVault { bool eagerInitComplete() const; size_t livingSingletonCount() const { - RWSpinLock::ReadHolder rh(&mutex_); + auto singletons = singletons_.rlock(); size_t ret = 0; - for (const auto& p : singletons_) { + for (const auto& p : *singletons) { if (p.second->hasLiveInstance()) { ++ret; } @@ -429,15 +454,21 @@ class SingletonVault { // tests only. template static SingletonVault* singleton() { - static SingletonVault* vault = new SingletonVault(); + /* library-local */ static auto vault = + detail::createGlobal(); return vault; } typedef std::string(*StackTraceGetterPtr)(); static std::atomic& stackTraceGetter() { - static std::atomic stackTraceGetterPtr; - return stackTraceGetterPtr; + /* library-local */ static auto stackTraceGetterPtr = detail:: + createGlobal, SingletonVault>(); + return *stackTraceGetterPtr; + } + + void setType(Type type) { + type_ = type; } private: @@ -450,13 +481,20 @@ class SingletonVault { Quiescing, }; + struct State { + SingletonVaultState state{SingletonVaultState::Running}; + bool registrationComplete{false}; + }; + // Each singleton in the vault can be in two states: dead // (registered but never created), living (CreateFunc returned an instance). - void stateCheck(SingletonVaultState expected, - const char* msg="Unexpected singleton state change") { - if (expected != state_) { - throw std::logic_error(msg); + static void stateCheck( + SingletonVaultState expected, + const State& state, + const char* msg = "Unexpected singleton state change") { + if (expected != state.state) { + throw std::logic_error(msg); } } @@ -476,15 +514,17 @@ class SingletonVault { typedef std::unordered_map SingletonMap; + folly::Synchronized singletons_; + folly::Synchronized> + eagerInitSingletons_; + folly::Synchronized> creationOrder_; - mutable folly::RWSpinLock mutex_; - SingletonMap singletons_; - std::unordered_set eagerInitSingletons_; - std::vector creation_order_; - SingletonVaultState state_{SingletonVaultState::Running}; - bool registrationComplete_{false}; - folly::RWSpinLock stateMutex_; - Type type_{Type::Relaxed}; + // Using SharedMutexReadPriority is important here, because we want to make + // sure we don't block nested singleton creation happening concurrently with + // destroyInstances(). + folly::Synchronized state_; + + Type type_; }; // This is the wrapper class that most users actually interact with. @@ -528,10 +568,9 @@ class Singleton { 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(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) { @@ -577,7 +616,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); } @@ -610,6 +649,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() { + /* library-local */ 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