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) {
35 throw std::logic_error("Double registration");
38 create_ = std::move(c);
39 teardown_ = std::move(t);
41 state_ = SingletonHolderState::Dead;
45 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
46 if (state_ == SingletonHolderState::NotRegistered) {
47 throw std::logic_error("Registering mock before singleton was registered");
51 std::lock_guard<std::mutex> entry_lock(mutex_);
53 create_ = std::move(c);
54 teardown_ = std::move(t);
58 T* SingletonHolder<T>::get() {
59 if (LIKELY(state_ == SingletonHolderState::Living)) {
64 if (instance_weak_.expired()) {
65 throw std::runtime_error(
66 "Raw pointer to a singleton requested after its destruction.");
73 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
74 if (UNLIKELY(state_ != SingletonHolderState::Living)) {
78 return instance_weak_;
82 TypeDescriptor SingletonHolder<T>::type() {
87 bool SingletonHolder<T>::hasLiveInstance() {
88 return !instance_weak_.expired();
92 void SingletonHolder<T>::destroyInstance() {
93 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.";
110 template <typename T>
111 SingletonHolder<T>::SingletonHolder(TypeDescriptor type__,
112 SingletonVault& vault) :
113 type_(type__), vault_(vault) {
116 template <typename T>
117 void SingletonHolder<T>::createInstance() {
118 // There's no synchronization here, so we may not see the current value
119 // for creating_thread if it was set by other thread, but we only care about
120 // it if it was set by current thread anyways.
121 if (creating_thread_ == std::this_thread::get_id()) {
122 throw std::out_of_range(std::string("circular singleton dependency: ") +
126 std::lock_guard<std::mutex> entry_lock(mutex_);
127 if (state_ == SingletonHolderState::Living) {
130 if (state_ == SingletonHolderState::NotRegistered) {
131 throw std::out_of_range("Creating instance for unregistered singleton");
134 if (state_ == SingletonHolderState::Living) {
138 creating_thread_ = std::this_thread::get_id();
140 RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
141 if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
142 creating_thread_ = std::thread::id();
146 auto destroy_baton = std::make_shared<folly::Baton<>>();
147 auto print_destructor_stack_trace =
148 std::make_shared<std::atomic<bool>>(false);
149 auto teardown = teardown_;
150 auto type_name = type_.name();
152 // Can't use make_shared -- no support for a custom deleter, sadly.
153 instance_ = std::shared_ptr<T>(
155 [destroy_baton, print_destructor_stack_trace, teardown, type_name]
156 (T* instance_ptr) mutable {
157 teardown(instance_ptr);
158 destroy_baton->post();
159 if (print_destructor_stack_trace->load()) {
160 std::string output = "Singleton " + type_name + " was destroyed.\n";
162 auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
163 auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
164 if (stack_trace.empty()) {
165 output += "Failed to get destructor stack trace.";
167 output += "Destructor stack trace:\n";
168 output += stack_trace;
171 LOG(ERROR) << output;
175 // We should schedule destroyInstances() only after the singleton was
176 // created. This will ensure it will be destroyed before singletons,
177 // not managed by folly::Singleton, which were initialized in its
179 SingletonVault::scheduleDestroyInstances();
181 instance_weak_ = instance_;
182 instance_ptr_ = instance_.get();
183 creating_thread_ = std::thread::id();
184 destroy_baton_ = std::move(destroy_baton);
185 print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
187 // This has to be the last step, because once state is Living other threads
188 // may access instance and instance_weak w/o synchronization.
189 state_.store(SingletonHolderState::Living);
192 RWSpinLock::WriteHolder wh(&vault_.mutex_);
193 vault_.creation_order_.push_back(type_);