/*
- * Copyright 2016 Facebook, Inc.
+ * Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
// 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<MyExpensiveService> getInstance();
+// ....
+// };
//
// In your .cpp file:
-// namespace { folly::Singleton<MyExpensiveService> the_singleton; }
+// namespace { struct PrivateTag {}; }
+// static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton;
+// std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() {
+// return the_singleton.try_get();
+// }
//
-// Code can access it via:
+// Code in other modules can access it via:
//
-// MyExpensiveService* instance = Singleton<MyExpensiveService>::get();
-// or
-// std::weak_ptr<MyExpensiveService> instance =
-// Singleton<MyExpensiveService>::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<ObjectType, TagType>::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
// 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<T>::try_get()
//
// namespace {
// struct Tag1 {};
// should call reenableInstances.
#pragma once
-#include <folly/Baton.h>
-#include <folly/Demangle.h>
+
#include <folly/Exception.h>
#include <folly/Executor.h>
-#include <folly/Hash.h>
#include <folly/Memory.h>
-#include <folly/RWSpinLock.h>
#include <folly/Synchronized.h>
#include <folly/detail/StaticSingletonManager.h>
#include <folly/experimental/ReadMostlySharedPtr.h>
+#include <folly/hash/Hash.h>
+#include <folly/synchronization/Baton.h>
+#include <folly/synchronization/RWSpinLock.h>
#include <algorithm>
#include <atomic>
return *this;
}
- std::string name() const {
- auto ret = demangle(ti_.name());
- if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
- ret += "/";
- ret += demangle(tag_ti_.name());
- }
- return ret.toStdString();
- }
+ std::string name() const;
friend class TypeDescriptorHasher;
}
};
+[[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
+ const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
+ const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
+ const TypeDescriptor& type);
+
+void singletonWarnDestroyInstanceLeak(
+ const TypeDescriptor& type,
+ const void* ptr);
+
+[[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
+ const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
+ const TypeDescriptor& type);
+
+[[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
+ const TypeDescriptor& type);
+
+void singletonPrintDestructionStackTrace(const TypeDescriptor& type);
+
+[[noreturn]] void singletonThrowNullCreator(const std::type_info& type);
+
+[[noreturn]] void singletonThrowGetInvokedAfterDestruction(
+ const TypeDescriptor& type);
+
+struct SingletonVaultState {
+ // The two stages of life for a vault, as mentioned in the class comment.
+ enum class Type {
+ Running,
+ Quiescing,
+ };
+
+ Type state{Type::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 check(
+ Type expected,
+ const char* msg = "Unexpected singleton state change") const {
+ if (expected != state) {
+ throwUnexpectedState(msg);
+ }
+ }
+
+ [[noreturn]] static void throwUnexpectedState(const char* msg);
+};
+
// This interface is used by SingletonVault to interact with SingletonHolders.
// Having a non-template interface allows SingletonVault to keep a list of all
// SingletonHolders.
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);
SingletonHolder(SingletonHolder&&) = delete;
};
-}
+} // namespace detail
class SingletonVault {
public:
}
};
- explicit SingletonVault(Type type = Type::Strict) : type_(type) {}
+ static Type defaultVaultType();
+
+ explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {}
// Destructor is only called by unit tests to check destroyInstances.
~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);
template <typename T>
friend struct detail::SingletonHolder;
- // The two stages of life for a vault, as mentioned in the class comment.
- enum class SingletonVaultState {
- Running,
- 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).
-
- static void stateCheck(
- SingletonVaultState expected,
- const State& state,
- const char* msg = "Unexpected singleton state change") {
- if (expected != state.state) {
- throw std::logic_error(msg);
- }
- }
-
// This method only matters if registrationComplete() is never called.
// Otherwise destroyInstances is scheduled to be executed atexit.
//
typedef std::unordered_map<detail::TypeDescriptor,
detail::SingletonHolderBase*,
detail::TypeDescriptorHasher> SingletonMap;
- folly::Synchronized<SingletonMap> singletons_;
- folly::Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
+ Synchronized<SingletonMap> singletons_;
+ Synchronized<std::unordered_set<detail::SingletonHolderBase*>>
eagerInitSingletons_;
- folly::Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
+ Synchronized<std::vector<detail::TypeDescriptor>> creationOrder_;
- folly::Synchronized<State> state_;
+ // Using SharedMutexReadPriority is important here, because we want to make
+ // sure we don't block nested singleton creation happening concurrently with
+ // destroyInstances().
+ Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_;
Type type_;
};
// singletons. Create instances of this class in the global scope of
// type Singleton<T> to register your singleton for later access via
// Singleton<T>::try_get().
-template <typename T,
- typename Tag = detail::DefaultTag,
- typename VaultTag = detail::DefaultTag /* for testing */>
+template <
+ typename T,
+ typename Tag = detail::DefaultTag,
+ typename VaultTag = detail::DefaultTag /* for testing */>
class Singleton {
public:
typedef std::function<T*(void)> CreateFunc;
explicit Singleton(typename Singleton::CreateFunc c,
typename Singleton::TeardownFunc t = nullptr) {
if (c == nullptr) {
- throw std::logic_error(
- "nullptr_t should be passed if you want T to be default constructed");
+ detail::singletonThrowNullCreator(typeid(T));
}
auto vault = SingletonVault::singleton<VaultTag>();
static void make_mock(CreateFunc c,
typename Singleton<T>::TeardownFunc t = nullptr) {
if (c == nullptr) {
- throw std::logic_error(
- "nullptr_t should be passed if you want T to be default constructed");
+ detail::singletonThrowNullCreator(typeid(T));
}
auto& entry = getEntry();
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() + ">";
+ detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_);
}
entry.createFunc = createFunc;
entry.state = State::Dead;
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) {
+ if (createFunc == nullptr) {
+ detail::singletonThrowNullCreator(typeid(T));
+ }
+
+ auto& entry = entryInstance();
+ entry.createFunc = createFunc;
+ entry.state = State::Dead;
+ }
+
private:
enum class State { NotRegistered, Dead, Living };
}
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)");
+ detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_);
}
entry.ptr = entry.createFunc();
entry.state = State::Living;
}
};
-}
+} // namespace folly
#include <folly/Singleton-inl.h>