2 * Copyright 2015 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 static auto entry = new SingletonHolder<T>(
25 {typeid(T), typeid(Tag)},
26 *SingletonVault::singleton<VaultTag>());
31 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
32 std::lock_guard<std::mutex> entry_lock(mutex_);
34 if (state_ != SingletonHolderState::NotRegistered) {
37 * You have two instances of the same
38 * folly::Singleton<Class>. Probably because you define the
39 * singleton in a header included in multiple places? In general,
40 * folly::Singleton shouldn't be in the header, only off in some
41 * anonymous namespace in a cpp file. Code needing the singleton
42 * will find it when that code references folly::Singleton<Class>.
44 * Alternatively, you could have 2 singletons with the same type
45 * defined with a different name in a .cpp (source) file. For
48 * Singleton<int> a([] { return new int(3); });
49 * Singleton<int> b([] { return new int(4); });
52 LOG(FATAL) << "Double registration of singletons of the same "
53 << "underlying type; check for multiple definitions "
54 << "of type folly::Singleton<" + type_.name() + ">";
57 create_ = std::move(c);
58 teardown_ = std::move(t);
60 state_ = SingletonHolderState::Dead;
64 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
65 if (state_ == SingletonHolderState::NotRegistered) {
67 << "Registering mock before singleton was registered: " << type_.name();
71 std::lock_guard<std::mutex> entry_lock(mutex_);
73 create_ = std::move(c);
74 teardown_ = std::move(t);
78 T* SingletonHolder<T>::get() {
79 if (LIKELY(state_.load(std::memory_order_acquire) ==
80 SingletonHolderState::Living)) {
85 if (instance_weak_.expired()) {
86 throw std::runtime_error(
87 "Raw pointer to a singleton requested after its destruction."
88 " Singleton type is: " +
96 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
97 if (UNLIKELY(state_.load(std::memory_order_acquire) !=
98 SingletonHolderState::Living)) {
102 return instance_weak_;
105 template <typename T>
106 std::shared_ptr<T> SingletonHolder<T>::try_get() {
107 if (UNLIKELY(state_.load(std::memory_order_acquire) !=
108 SingletonHolderState::Living)) {
112 return instance_weak_.lock();
115 template <typename T>
116 TypeDescriptor SingletonHolder<T>::type() {
120 template <typename T>
121 bool SingletonHolder<T>::hasLiveInstance() {
122 return !instance_weak_.expired();
125 template <typename T>
126 void SingletonHolder<T>::destroyInstance() {
127 state_ = SingletonHolderState::Dead;
129 if (destroy_baton_) {
130 auto wait_result = destroy_baton_->timed_wait(
131 std::chrono::steady_clock::now() + kDestroyWaitTime);
133 print_destructor_stack_trace_->store(true);
134 LOG(ERROR) << "Singleton of type " << type_.name() << " has a "
135 << "living reference at destroyInstances time; beware! Raw "
136 << "pointer is " << instance_ptr_ << ". It is very likely "
137 << "that some other singleton is holding a shared_ptr to it. "
138 << "Make sure dependencies between these singletons are "
139 << "properly defined.";
144 template <typename T>
145 SingletonHolder<T>::SingletonHolder(TypeDescriptor type__,
146 SingletonVault& vault) :
147 type_(type__), vault_(vault) {
150 template <typename T>
151 bool SingletonHolder<T>::creationStarted() {
152 // If alive, then creation was of course started.
153 // This is flipped after creating_thread_ was set, and before it was reset.
154 if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
158 // Not yet built. Is it currently in progress?
159 if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
166 template <typename T>
167 void SingletonHolder<T>::createInstance() {
168 if (creating_thread_.load(std::memory_order_acquire) ==
169 std::this_thread::get_id()) {
170 LOG(FATAL) << "circular singleton dependency: " << type_.name();
173 std::lock_guard<std::mutex> entry_lock(mutex_);
174 if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
177 if (state_.load(std::memory_order_acquire) ==
178 SingletonHolderState::NotRegistered) {
179 auto ptr = SingletonVault::stackTraceGetter().load();
180 LOG(FATAL) << "Creating instance for unregistered singleton: "
181 << type_.name() << "\n"
183 << "\n" << (ptr ? (*ptr)() : "(not available)");
186 if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
191 // Clean up creator thread when complete, and also, in case of errors here,
192 // so that subsequent attempts don't think this is still in the process of
194 creating_thread_.store(std::thread::id(), std::memory_order_release);
197 creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
199 RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
200 if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
204 auto destroy_baton = std::make_shared<folly::Baton<>>();
205 auto print_destructor_stack_trace =
206 std::make_shared<std::atomic<bool>>(false);
207 auto teardown = teardown_;
208 auto type_name = type_.name();
210 // Can't use make_shared -- no support for a custom deleter, sadly.
211 instance_ = std::shared_ptr<T>(
213 [destroy_baton, print_destructor_stack_trace, teardown, type_name]
214 (T* instance_ptr) mutable {
215 teardown(instance_ptr);
216 destroy_baton->post();
217 if (print_destructor_stack_trace->load()) {
218 std::string output = "Singleton " + type_name + " was destroyed.\n";
220 auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
221 auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
222 if (stack_trace.empty()) {
223 output += "Failed to get destructor stack trace.";
225 output += "Destructor stack trace:\n";
226 output += stack_trace;
229 LOG(ERROR) << output;
233 // We should schedule destroyInstances() only after the singleton was
234 // created. This will ensure it will be destroyed before singletons,
235 // not managed by folly::Singleton, which were initialized in its
237 SingletonVault::scheduleDestroyInstances();
239 instance_weak_ = instance_;
240 instance_ptr_ = instance_.get();
241 destroy_baton_ = std::move(destroy_baton);
242 print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
244 // This has to be the last step, because once state is Living other threads
245 // may access instance and instance_weak w/o synchronization.
246 state_.store(SingletonHolderState::Living, std::memory_order_release);
249 RWSpinLock::WriteHolder wh(&vault_.mutex_);
250 vault_.creation_order_.push_back(type_);