Adds writer test case for RCU
[folly.git] / folly / Singleton-inl.h
1 /*
2  * Copyright 2015-present 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   /* 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>());
28       });
29   return *entry;
30 }
31
32 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
33     const TypeDescriptor& type);
34
35 template <typename T>
36 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
37   std::lock_guard<std::mutex> entry_lock(mutex_);
38
39   if (state_ != SingletonHolderState::NotRegistered) {
40     /* Possible causes:
41      *
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>.
48      *
49      * Alternatively, you could have 2 singletons with the same type
50      * defined with a different name in a .cpp (source) file. For
51      * example:
52      *
53      * Singleton<int> a([] { return new int(3); });
54      * Singleton<int> b([] { return new int(4); });
55      *
56      */
57     singletonWarnDoubleRegistrationAndAbort(type());
58   }
59
60   create_ = std::move(c);
61   teardown_ = std::move(t);
62
63   state_ = SingletonHolderState::Dead;
64 }
65
66 template <typename T>
67 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
68   if (state_ == SingletonHolderState::NotRegistered) {
69     detail::singletonWarnRegisterMockEarlyAndAbort(type());
70   }
71   if (state_ == SingletonHolderState::Living) {
72     destroyInstance();
73   }
74
75   {
76     auto creationOrder = vault_.creationOrder_.wlock();
77
78     auto it = std::find(creationOrder->begin(), creationOrder->end(), type());
79     if (it != creationOrder->end()) {
80       creationOrder->erase(it);
81     }
82   }
83
84   std::lock_guard<std::mutex> entry_lock(mutex_);
85
86   create_ = std::move(c);
87   teardown_ = std::move(t);
88 }
89
90 template <typename T>
91 T* SingletonHolder<T>::get() {
92   if (LIKELY(state_.load(std::memory_order_acquire) ==
93              SingletonHolderState::Living)) {
94     return instance_ptr_;
95   }
96   createInstance();
97
98   if (instance_weak_.expired()) {
99     detail::singletonThrowGetInvokedAfterDestruction(type());
100   }
101
102   return instance_ptr_;
103 }
104
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)) {
109     createInstance();
110   }
111
112   return instance_weak_;
113 }
114
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)) {
119     createInstance();
120   }
121
122   return instance_weak_.lock();
123 }
124
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)) {
129     createInstance();
130   }
131
132   return instance_weak_fast_.lock();
133 }
134
135 template <typename T>
136 bool SingletonHolder<T>::hasLiveInstance() {
137   return !instance_weak_.expired();
138 }
139
140 template <typename T>
141 void SingletonHolder<T>::preDestroyInstance(
142     ReadMostlyMainPtrDeleter<>& deleter) {
143   instance_copy_ = instance_;
144   deleter.add(std::move(instance_));
145 }
146
147 template <typename T>
148 void SingletonHolder<T>::destroyInstance() {
149   state_ = SingletonHolderState::Dead;
150   instance_.reset();
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_);
158     } else {
159       print_destructor_stack_trace_->store(true);
160       detail::singletonWarnDestroyInstanceLeak(type(), instance_ptr_);
161     }
162   }
163 }
164
165 template <typename T>
166 SingletonHolder<T>::SingletonHolder(
167     TypeDescriptor typeDesc,
168     SingletonVault& vault)
169     : SingletonHolderBase(typeDesc), vault_(vault) {}
170
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) {
176     return true;
177   }
178
179   // Not yet built.  Is it currently in progress?
180   if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
181     return true;
182   }
183
184   return false;
185 }
186
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());
192   }
193
194   std::lock_guard<std::mutex> entry_lock(mutex_);
195   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
196     return;
197   }
198   if (state_.load(std::memory_order_acquire) ==
199         SingletonHolderState::NotRegistered) {
200     detail::singletonWarnCreateUnregisteredAndAbort(type());
201   }
202
203   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
204     return;
205   }
206
207   SCOPE_EXIT {
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
210     // being built.
211     creating_thread_.store(std::thread::id(), std::memory_order_release);
212   };
213
214   creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
215
216   auto state = vault_.state_.rlock();
217   if (vault_.type_ != SingletonVault::Type::Relaxed &&
218       !state->registrationComplete) {
219     detail::singletonWarnCreateBeforeRegistrationCompleteAndAbort(type());
220   }
221   if (state->state == detail::SingletonVaultState::Type::Quiescing) {
222     return;
223   }
224
225   auto destroy_baton = std::make_shared<folly::Baton<>>();
226   auto print_destructor_stack_trace =
227     std::make_shared<std::atomic<bool>>(false);
228
229   // Can't use make_shared -- no support for a custom deleter, sadly.
230   std::shared_ptr<T> instance(
231       create_(),
232       [ destroy_baton, print_destructor_stack_trace, type = type() ](
233           T*) mutable {
234         destroy_baton->post();
235         if (print_destructor_stack_trace->load()) {
236           detail::singletonPrintDestructionStackTrace(type);
237         }
238       });
239
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
243   // constructor
244   SingletonVault::scheduleDestroyInstances();
245
246   instance_weak_ = instance;
247   instance_ptr_ = instance.get();
248   instance_.reset(std::move(instance));
249   instance_weak_fast_ = instance_;
250
251   destroy_baton_ = std::move(destroy_baton);
252   print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
253
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);
257
258   vault_.creationOrder_.wlock()->push_back(type());
259 }
260
261 } // namespace detail
262
263 } // namespace folly