2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 template <typename Tag, typename VaultTag>
23 SingletonHolder<T>& SingletonHolder<T>::singleton() {
24 /* library-local */ static auto entry =
25 createGlobal<SingletonHolder<T>, std::pair<Tag, VaultTag>>([]() {
26 return new SingletonHolder<T>({typeid(T), typeid(Tag)},
27 *SingletonVault::singleton<VaultTag>());
32 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
33 const TypeDescriptor& type);
36 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
37 std::lock_guard<std::mutex> entry_lock(mutex_);
39 if (state_ != SingletonHolderState::NotRegistered) {
42 * You have two instances of the same
43 * folly::Singleton<Class>. Probably because you define the
44 * singleton in a header included in multiple places? In general,
45 * folly::Singleton shouldn't be in the header, only off in some
46 * anonymous namespace in a cpp file. Code needing the singleton
47 * will find it when that code references folly::Singleton<Class>.
49 * Alternatively, you could have 2 singletons with the same type
50 * defined with a different name in a .cpp (source) file. For
53 * Singleton<int> a([] { return new int(3); });
54 * Singleton<int> b([] { return new int(4); });
57 singletonWarnDoubleRegistrationAndAbort(type());
60 create_ = std::move(c);
61 teardown_ = std::move(t);
63 state_ = SingletonHolderState::Dead;
67 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
68 if (state_ == SingletonHolderState::NotRegistered) {
69 detail::singletonWarnRegisterMockEarlyAndAbort(type());
71 if (state_ == SingletonHolderState::Living) {
76 auto creationOrder = vault_.creationOrder_.wlock();
78 auto it = std::find(creationOrder->begin(), creationOrder->end(), type());
79 if (it != creationOrder->end()) {
80 creationOrder->erase(it);
84 std::lock_guard<std::mutex> entry_lock(mutex_);
86 create_ = std::move(c);
87 teardown_ = std::move(t);
91 T* SingletonHolder<T>::get() {
92 if (LIKELY(state_.load(std::memory_order_acquire) ==
93 SingletonHolderState::Living)) {
98 if (instance_weak_.expired()) {
99 detail::singletonThrowGetInvokedAfterDestruction(type());
102 return instance_ptr_;
105 template <typename T>
106 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
107 if (UNLIKELY(state_.load(std::memory_order_acquire) !=
108 SingletonHolderState::Living)) {
112 return instance_weak_;
115 template <typename T>
116 std::shared_ptr<T> SingletonHolder<T>::try_get() {
117 if (UNLIKELY(state_.load(std::memory_order_acquire) !=
118 SingletonHolderState::Living)) {
122 return instance_weak_.lock();
125 template <typename T>
126 folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
127 if (UNLIKELY(state_.load(std::memory_order_acquire) !=
128 SingletonHolderState::Living)) {
132 return instance_weak_fast_.lock();
135 template <typename T>
136 bool SingletonHolder<T>::hasLiveInstance() {
137 return !instance_weak_.expired();
140 template <typename T>
141 void SingletonHolder<T>::preDestroyInstance(
142 ReadMostlyMainPtrDeleter<>& deleter) {
143 instance_copy_ = instance_;
144 deleter.add(std::move(instance_));
147 template <typename T>
148 void SingletonHolder<T>::destroyInstance() {
149 state_ = SingletonHolderState::Dead;
151 instance_copy_.reset();
152 if (destroy_baton_) {
153 constexpr std::chrono::seconds kDestroyWaitTime{5};
154 auto last_reference_released =
155 destroy_baton_->try_wait_for(kDestroyWaitTime);
156 if (last_reference_released) {
157 teardown_(instance_ptr_);
159 print_destructor_stack_trace_->store(true);
160 detail::singletonWarnDestroyInstanceLeak(type(), instance_ptr_);
165 template <typename T>
166 SingletonHolder<T>::SingletonHolder(
167 TypeDescriptor typeDesc,
168 SingletonVault& vault)
169 : SingletonHolderBase(typeDesc), vault_(vault) {}
171 template <typename T>
172 bool SingletonHolder<T>::creationStarted() {
173 // If alive, then creation was of course started.
174 // This is flipped after creating_thread_ was set, and before it was reset.
175 if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
179 // Not yet built. Is it currently in progress?
180 if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
187 template <typename T>
188 void SingletonHolder<T>::createInstance() {
189 if (creating_thread_.load(std::memory_order_acquire) ==
190 std::this_thread::get_id()) {
191 detail::singletonWarnCreateCircularDependencyAndAbort(type());
194 std::lock_guard<std::mutex> entry_lock(mutex_);
195 if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
198 if (state_.load(std::memory_order_acquire) ==
199 SingletonHolderState::NotRegistered) {
200 detail::singletonWarnCreateUnregisteredAndAbort(type());
203 if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
208 // Clean up creator thread when complete, and also, in case of errors here,
209 // so that subsequent attempts don't think this is still in the process of
211 creating_thread_.store(std::thread::id(), std::memory_order_release);
214 creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
216 auto state = vault_.state_.rlock();
217 if (vault_.type_ != SingletonVault::Type::Relaxed &&
218 !state->registrationComplete) {
219 detail::singletonWarnCreateBeforeRegistrationCompleteAndAbort(type());
221 if (state->state == detail::SingletonVaultState::Type::Quiescing) {
225 auto destroy_baton = std::make_shared<folly::Baton<>>();
226 auto print_destructor_stack_trace =
227 std::make_shared<std::atomic<bool>>(false);
229 // Can't use make_shared -- no support for a custom deleter, sadly.
230 std::shared_ptr<T> instance(
232 [ destroy_baton, print_destructor_stack_trace, type = type() ](
234 destroy_baton->post();
235 if (print_destructor_stack_trace->load()) {
236 detail::singletonPrintDestructionStackTrace(type);
240 // We should schedule destroyInstances() only after the singleton was
241 // created. This will ensure it will be destroyed before singletons,
242 // not managed by folly::Singleton, which were initialized in its
244 SingletonVault::scheduleDestroyInstances();
246 instance_weak_ = instance;
247 instance_ptr_ = instance.get();
248 instance_.reset(std::move(instance));
249 instance_weak_fast_ = instance_;
251 destroy_baton_ = std::move(destroy_baton);
252 print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
254 // This has to be the last step, because once state is Living other threads
255 // may access instance and instance_weak w/o synchronization.
256 state_.store(SingletonHolderState::Living, std::memory_order_release);
258 vault_.creationOrder_.wlock()->push_back(type());
261 } // namespace detail