X-Git-Url: http://plrg.eecs.uci.edu/git/?p=folly.git;a=blobdiff_plain;f=folly%2FSingleton.h;h=921c443ab3eeca0ff200894cedb82a8720aba1aa;hp=c377f3ad02c49c6b3cc2a6f233d7c80371edb15c;hb=5acf7b9277cbead28d6a3e5042aed8b7de109e35;hpb=0416e1ea440f816d5543feb5e834f09906ddfcab diff --git a/folly/Singleton.h b/folly/Singleton.h index c377f3ad..921c443a 100644 --- a/folly/Singleton.h +++ b/folly/Singleton.h @@ -1,5 +1,5 @@ /* - * Copyright 2016 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 {}; @@ -111,16 +121,16 @@ // should call reenableInstances. #pragma once -#include #include #include #include -#include #include #include #include #include #include +#include +#include #include #include @@ -263,11 +273,11 @@ struct SingletonHolder : public SingletonHolderBase { void registerSingleton(CreateFunc c, TeardownFunc t); void registerSingletonMock(CreateFunc c, TeardownFunc t); - virtual bool hasLiveInstance() override; - virtual void createInstance() override; - virtual bool creationStarted() override; - virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override; - virtual void destroyInstance() override; + bool hasLiveInstance() override; + void createInstance() override; + bool creationStarted() override; + void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override; + void destroyInstance() override; private: SingletonHolder(TypeDescriptor type, SingletonVault& vault); @@ -318,7 +328,7 @@ struct SingletonHolder : public SingletonHolderBase { SingletonHolder(SingletonHolder&&) = delete; }; -} +} // namespace detail class SingletonVault { public: @@ -348,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(); @@ -393,10 +405,10 @@ class SingletonVault { * * Sample usage: * - * wangle::IOThreadPoolExecutor executor(max_concurrency_level); + * folly::IOThreadPoolExecutor executor(max_concurrency_level); * folly::Baton<> done; * doEagerInitVia(executor, &done); - * done.wait(); // or 'timed_wait', or spin with 'try_wait' + * done.wait(); // or 'try_wait_for', etc. * */ void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr); @@ -507,9 +519,12 @@ class SingletonVault { eagerInitSingletons_; folly::Synchronized> creationOrder_; - folly::Synchronized state_; + // 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_{Type::Relaxed}; + Type type_; }; // This is the wrapper class that most users actually interact with. @@ -517,9 +532,10 @@ class SingletonVault { // singletons. Create instances of this class in the global scope of // type Singleton to register your singleton for later access via // Singleton::try_get(). -template +template < + typename T, + typename Tag = detail::DefaultTag, + typename VaultTag = detail::DefaultTag /* for testing */> class Singleton { public: typedef std::function CreateFunc; @@ -654,6 +670,21 @@ class LeakySingleton { static T& get() { return instance(); } + static void make_mock(std::nullptr_t /* c */ = nullptr) { + make_mock([]() { return new T; }); + } + + static void make_mock(CreateFunc createFunc) { + auto& entry = entryInstance(); + if (createFunc == nullptr) { + throw std::logic_error( + "nullptr_t should be passed if you want T to be default constructed"); + } + + entry.createFunc = createFunc; + entry.state = State::Dead; + } + private: enum class State { NotRegistered, Dead, Living }; @@ -703,6 +734,6 @@ class LeakySingleton { entry.state = State::Living; } }; -} +} // namespace folly #include