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.
16 #include <folly/experimental/symbolizer/Symbolizer.h>
23 template <typename Tag, typename VaultTag>
24 SingletonHolder<T>& SingletonHolder<T>::singleton() {
25 static auto entry = new SingletonHolder<T>(
26 {typeid(T), typeid(Tag)},
27 *SingletonVault::singleton<VaultTag>());
32 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
33 std::lock_guard<std::mutex> entry_lock(mutex_);
35 if (state_ != SingletonHolderState::NotRegistered) {
36 throw std::logic_error("Double registration");
39 create_ = std::move(c);
40 teardown_ = std::move(t);
42 state_ = SingletonHolderState::Dead;
46 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
47 if (state_ == SingletonHolderState::NotRegistered) {
48 throw std::logic_error("Registering mock before singleton was registered");
52 std::lock_guard<std::mutex> entry_lock(mutex_);
54 create_ = std::move(c);
55 teardown_ = std::move(t);
59 T* SingletonHolder<T>::get() {
60 if (LIKELY(state_ == SingletonHolderState::Living)) {
65 if (instance_weak_.expired()) {
66 throw std::runtime_error(
67 "Raw pointer to a singleton requested after its destruction.");
74 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
75 if (UNLIKELY(state_ != SingletonHolderState::Living)) {
79 return instance_weak_;
83 TypeDescriptor SingletonHolder<T>::type() {
88 bool SingletonHolder<T>::hasLiveInstance() {
89 return state_ == SingletonHolderState::Living;
93 void SingletonHolder<T>::destroyInstance() {
94 state_ = SingletonHolderState::Dead;
96 auto wait_result = destroy_baton_->timed_wait(
97 std::chrono::steady_clock::now() + kDestroyWaitTime);
99 print_destructor_stack_trace_->store(true);
100 LOG(ERROR) << "Singleton of type " << type_.name() << " has a "
101 << "living reference at destroyInstances time; beware! Raw "
102 << "pointer is " << instance_ptr_ << ". It is very likely "
103 << "that some other singleton is holding a shared_ptr to it. "
104 << "Make sure dependencies between these singletons are "
105 << "properly defined.";
109 template <typename T>
110 SingletonHolder<T>::SingletonHolder(TypeDescriptor type__,
111 SingletonVault& vault) :
112 type_(type__), vault_(vault) {
115 template <typename T>
116 void SingletonHolder<T>::createInstance() {
117 // There's no synchronization here, so we may not see the current value
118 // for creating_thread if it was set by other thread, but we only care about
119 // it if it was set by current thread anyways.
120 if (creating_thread_ == std::this_thread::get_id()) {
121 throw std::out_of_range(std::string("circular singleton dependency: ") +
125 std::lock_guard<std::mutex> entry_lock(mutex_);
126 if (state_ == SingletonHolderState::Living) {
129 if (state_ == SingletonHolderState::NotRegistered) {
130 throw std::out_of_range("Creating instance for unregistered singleton");
133 if (state_ == SingletonHolderState::Living) {
137 creating_thread_ = std::this_thread::get_id();
139 RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
140 if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
141 creating_thread_ = std::thread::id();
145 auto destroy_baton = std::make_shared<folly::Baton<>>();
146 auto print_destructor_stack_trace =
147 std::make_shared<std::atomic<bool>>(false);
148 auto teardown = teardown_;
149 auto type_name = type_.name();
151 // Can't use make_shared -- no support for a custom deleter, sadly.
152 instance_ = std::shared_ptr<T>(
154 [destroy_baton, print_destructor_stack_trace, teardown, type_name]
155 (T* instance_ptr) mutable {
156 teardown(instance_ptr);
157 destroy_baton->post();
158 if (print_destructor_stack_trace->load()) {
159 std::string output = "Singleton " + type_name + " was destroyed.\n";
161 auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
162 auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
163 if (stack_trace.empty()) {
164 output += "Failed to get destructor stack trace.";
166 output += "Destructor stack trace:\n";
167 output += stack_trace;
170 LOG(ERROR) << output;
174 // We should schedule destroyInstances() only after the singleton was
175 // created. This will ensure it will be destroyed before singletons,
176 // not managed by folly::Singleton, which were initialized in its
178 SingletonVault::scheduleDestroyInstances();
180 instance_weak_ = instance_;
181 instance_ptr_ = instance_.get();
182 creating_thread_ = std::thread::id();
183 destroy_baton_ = std::move(destroy_baton);
184 print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
186 // This has to be the last step, because once state is Living other threads
187 // may access instance and instance_weak w/o synchronization.
188 state_.store(SingletonHolderState::Living);
191 RWSpinLock::WriteHolder wh(&vault_.mutex_);
192 vault_.creation_order_.push_back(type_);