Commit 5eb853a0 authored by Chip Turner's avatar Chip Turner Committed by Facebook Github Bot

Add vivify method to folly::Singleton

Summary:
This method ensures the singleton exists with less overhead than
calling `try_get` or `try_get_fast`.

Reviewed By: yfeldblum

Differential Revision: D8020292

fbshipit-source-id: 470ebea9fdb07e46a469c820f9149d6fc5af5d2f
parent a574e130
......@@ -132,6 +132,15 @@ folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
return instance_weak_fast_.lock();
}
template <typename T>
void SingletonHolder<T>::vivify() {
if (UNLIKELY(
state_.load(std::memory_order_relaxed) !=
SingletonHolderState::Living)) {
createInstance();
}
}
template <typename T>
bool SingletonHolder<T>::hasLiveInstance() {
return !instance_weak_.expired();
......
......@@ -314,6 +314,7 @@ struct SingletonHolder : public SingletonHolderBase {
inline std::weak_ptr<T> get_weak();
inline std::shared_ptr<T> try_get();
inline folly::ReadMostlySharedPtr<T> try_get_fast();
inline void vivify();
void registerSingleton(CreateFunc c, TeardownFunc t);
void registerSingletonMock(CreateFunc c, TeardownFunc t);
......@@ -590,6 +591,11 @@ class Singleton {
return getEntry().try_get_fast();
}
// Quickly ensure the instance exists.
static void vivify() {
getEntry().vivify();
}
explicit Singleton(std::nullptr_t /* _ */ = nullptr,
typename Singleton::TeardownFunc t = nullptr)
: Singleton([]() { return new T; }, std::move(t)) {}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment