Adding a unit test for HHWheelTimer exercising the default timeout functionality.
[folly.git] / folly / Singleton-inl.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 namespace folly {
18
19 namespace detail {
20
21 template <typename T>
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>());
27   return *entry;
28 }
29
30 template <typename T>
31 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
32   std::lock_guard<std::mutex> entry_lock(mutex_);
33
34   if (state_ != SingletonHolderState::NotRegistered) {
35     /* Possible causes:
36      *
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>.
43      *
44      * Alternatively, you could have 2 singletons with the same type
45      * defined with a different name in a .cpp (source) file. For
46      * example:
47      *
48      * Singleton<int> a([] { return new int(3); });
49      * Singleton<int> b([] { return new int(4); });
50      *
51      */
52     LOG(FATAL) << "Double registration of singletons of the same "
53                << "underlying type; check for multiple definitions "
54                << "of type folly::Singleton<" + type_.name() + ">";
55   }
56
57   create_ = std::move(c);
58   teardown_ = std::move(t);
59
60   state_ = SingletonHolderState::Dead;
61 }
62
63 template <typename T>
64 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
65   if (state_ == SingletonHolderState::NotRegistered) {
66     LOG(FATAL)
67         << "Registering mock before singleton was registered: " << type_.name();
68   }
69   destroyInstance();
70
71   std::lock_guard<std::mutex> entry_lock(mutex_);
72
73   create_ = std::move(c);
74   teardown_ = std::move(t);
75 }
76
77 template <typename T>
78 T* SingletonHolder<T>::get() {
79   if (LIKELY(state_ == SingletonHolderState::Living)) {
80     return instance_ptr_;
81   }
82   createInstance();
83
84   if (instance_weak_.expired()) {
85     throw std::runtime_error(
86         "Raw pointer to a singleton requested after its destruction."
87         " Singleton type is: " +
88         type_.name());
89   }
90
91   return instance_ptr_;
92 }
93
94 template <typename T>
95 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
96   if (UNLIKELY(state_ != SingletonHolderState::Living)) {
97     createInstance();
98   }
99
100   return instance_weak_;
101 }
102
103 template <typename T>
104 TypeDescriptor SingletonHolder<T>::type() {
105   return type_;
106 }
107
108 template <typename T>
109 bool SingletonHolder<T>::hasLiveInstance() {
110   return !instance_weak_.expired();
111 }
112
113 template <typename T>
114 void SingletonHolder<T>::destroyInstance() {
115   state_ = SingletonHolderState::Dead;
116   instance_.reset();
117   if (destroy_baton_) {
118     auto wait_result = destroy_baton_->timed_wait(
119       std::chrono::steady_clock::now() + kDestroyWaitTime);
120     if (!wait_result) {
121       print_destructor_stack_trace_->store(true);
122       LOG(ERROR) << "Singleton of type " << type_.name() << " has a "
123                  << "living reference at destroyInstances time; beware! Raw "
124                  << "pointer is " << instance_ptr_ << ". It is very likely "
125                  << "that some other singleton is holding a shared_ptr to it. "
126                  << "Make sure dependencies between these singletons are "
127                  << "properly defined.";
128     }
129   }
130 }
131
132 template <typename T>
133 SingletonHolder<T>::SingletonHolder(TypeDescriptor type__,
134                                     SingletonVault& vault) :
135     type_(type__), vault_(vault) {
136 }
137
138 template <typename T>
139 void SingletonHolder<T>::createInstance() {
140   // There's no synchronization here, so we may not see the current value
141   // for creating_thread if it was set by other thread, but we only care about
142   // it if it was set by current thread anyways.
143   if (creating_thread_ == std::this_thread::get_id()) {
144     LOG(FATAL) << "circular singleton dependency: " << type_.name();
145   }
146
147   std::lock_guard<std::mutex> entry_lock(mutex_);
148   if (state_ == SingletonHolderState::Living) {
149     return;
150   }
151   if (state_ == SingletonHolderState::NotRegistered) {
152     auto ptr = SingletonVault::stackTraceGetter().load();
153     LOG(FATAL) << "Creating instance for unregistered singleton: "
154                << type_.name() << "\n"
155                << "Stacktrace:"
156                << "\n" << (ptr ? (*ptr)() : "(not available)");
157   }
158
159   if (state_ == SingletonHolderState::Living) {
160     return;
161   }
162
163   SCOPE_EXIT {
164     // Clean up creator thread when complete, and also, in case of errors here,
165     // so that subsequent attempts don't think this is still in the process of
166     // being built.
167     creating_thread_ = std::thread::id();
168   };
169
170   creating_thread_ = std::this_thread::get_id();
171
172   RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
173   if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
174     return;
175   }
176
177   auto destroy_baton = std::make_shared<folly::Baton<>>();
178   auto print_destructor_stack_trace =
179     std::make_shared<std::atomic<bool>>(false);
180   auto teardown = teardown_;
181   auto type_name = type_.name();
182
183   // Can't use make_shared -- no support for a custom deleter, sadly.
184   instance_ = std::shared_ptr<T>(
185     create_(),
186     [destroy_baton, print_destructor_stack_trace, teardown, type_name]
187     (T* instance_ptr) mutable {
188       teardown(instance_ptr);
189       destroy_baton->post();
190       if (print_destructor_stack_trace->load()) {
191         std::string output = "Singleton " + type_name + " was destroyed.\n";
192
193         auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
194         auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
195         if (stack_trace.empty()) {
196           output += "Failed to get destructor stack trace.";
197         } else {
198           output += "Destructor stack trace:\n";
199           output += stack_trace;
200         }
201
202         LOG(ERROR) << output;
203       }
204     });
205
206   // We should schedule destroyInstances() only after the singleton was
207   // created. This will ensure it will be destroyed before singletons,
208   // not managed by folly::Singleton, which were initialized in its
209   // constructor
210   SingletonVault::scheduleDestroyInstances();
211
212   instance_weak_ = instance_;
213   instance_ptr_ = instance_.get();
214   destroy_baton_ = std::move(destroy_baton);
215   print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
216
217   // This has to be the last step, because once state is Living other threads
218   // may access instance and instance_weak w/o synchronization.
219   state_.store(SingletonHolderState::Living);
220
221   {
222     RWSpinLock::WriteHolder wh(&vault_.mutex_);
223     vault_.creation_order_.push_back(type_);
224   }
225 }
226
227 }
228
229 }