2 * Copyright 2017 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.
17 #include <folly/Singleton.h>
25 #include <folly/ScopeGuard.h>
31 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
32 const TypeDescriptor& type) {
33 // Ensure the availability of std::cerr
34 std::ios_base::Init ioInit;
35 std::cerr << "Double registration of singletons of the same "
36 "underlying type; check for multiple definitions "
37 "of type folly::Singleton<"
38 << type.name() << ">\n";
47 if (!leakedSingletons_.empty()) {
48 std::string leakedTypes;
49 for (const auto& singleton : leakedSingletons_) {
50 leakedTypes += "\t" + singleton.name() + "\n";
52 LOG(DFATAL) << "Singletons of the following types had living references "
53 << "after destroyInstances was finished:\n" << leakedTypes
54 << "beware! It is very likely that those singleton instances "
59 std::vector<detail::TypeDescriptor> leakedSingletons_;
62 #if defined(__APPLE__) || defined(_MSC_VER)
63 // OS X doesn't support constructor priorities.
64 FatalHelper fatalHelper;
66 FatalHelper __attribute__ ((__init_priority__ (101))) fatalHelper;
71 SingletonVault::~SingletonVault() { destroyInstances(); }
73 void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
74 auto state = state_.rlock();
75 stateCheck(SingletonVaultState::Running, *state);
77 if (UNLIKELY(state->registrationComplete)) {
78 LOG(ERROR) << "Registering singleton after registrationComplete().";
81 auto singletons = singletons_.wlock();
83 singletons->emplace(entry->type(), entry).second, std::logic_error);
86 void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
87 auto state = state_.rlock();
88 stateCheck(SingletonVaultState::Running, *state);
90 if (UNLIKELY(state->registrationComplete)) {
91 LOG(ERROR) << "Registering for eager-load after registrationComplete().";
94 CHECK_THROW(singletons_.rlock()->count(entry->type()), std::logic_error);
96 auto eagerInitSingletons = eagerInitSingletons_.wlock();
97 eagerInitSingletons->insert(entry);
100 void SingletonVault::registrationComplete() {
101 std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
103 auto state = state_.wlock();
104 stateCheck(SingletonVaultState::Running, *state);
106 if (state->registrationComplete) {
110 auto singletons = singletons_.rlock();
111 if (type_ == Type::Strict) {
112 for (const auto& p : *singletons) {
113 if (p.second->hasLiveInstance()) {
114 throw std::runtime_error(
115 "Singleton " + p.first.name() +
116 " created before registration was complete.");
121 state->registrationComplete = true;
124 void SingletonVault::doEagerInit() {
126 auto state = state_.rlock();
127 stateCheck(SingletonVaultState::Running, *state);
128 if (UNLIKELY(!state->registrationComplete)) {
129 throw std::logic_error("registrationComplete() not yet called");
133 auto eagerInitSingletons = eagerInitSingletons_.rlock();
134 for (auto* single : *eagerInitSingletons) {
135 single->createInstance();
139 void SingletonVault::doEagerInitVia(Executor& exe, folly::Baton<>* done) {
141 auto state = state_.rlock();
142 stateCheck(SingletonVaultState::Running, *state);
143 if (UNLIKELY(!state->registrationComplete)) {
144 throw std::logic_error("registrationComplete() not yet called");
148 auto eagerInitSingletons = eagerInitSingletons_.rlock();
150 std::make_shared<std::atomic<size_t>>(eagerInitSingletons->size());
151 for (auto* single : *eagerInitSingletons) {
152 // countdown is retained by shared_ptr, and will be alive until last lambda
153 // is done. notifyBaton is provided by the caller, and expected to remain
154 // present (if it's non-nullptr). singletonSet can go out of scope but
155 // its values, which are SingletonHolderBase pointers, are alive as long as
156 // SingletonVault is not being destroyed.
158 // decrement counter and notify if requested, whether initialization
159 // was successful, was skipped (already initialized), or exception thrown.
161 if (--(*countdown) == 0) {
162 if (done != nullptr) {
167 // if initialization is in progress in another thread, don't try to init
168 // here. Otherwise the current thread will block on 'createInstance'.
169 if (!single->creationStarted()) {
170 single->createInstance();
176 void SingletonVault::destroyInstances() {
177 auto stateW = state_.wlock();
178 if (stateW->state == SingletonVaultState::Quiescing) {
181 stateW->state = SingletonVaultState::Quiescing;
183 auto stateR = stateW.moveFromWriteToRead();
185 auto singletons = singletons_.rlock();
186 auto creationOrder = creationOrder_.rlock();
188 CHECK_GE(singletons->size(), creationOrder->size());
190 // Release all ReadMostlyMainPtrs at once
192 ReadMostlyMainPtrDeleter<> deleter;
193 for (auto& singleton_type : *creationOrder) {
194 singletons->at(singleton_type)->preDestroyInstance(deleter);
198 for (auto type_iter = creationOrder->rbegin();
199 type_iter != creationOrder->rend();
201 singletons->at(*type_iter)->destroyInstance();
204 for (auto& singleton_type : *creationOrder) {
205 auto singleton = singletons->at(singleton_type);
206 if (!singleton->hasLiveInstance()) {
210 fatalHelper.leakedSingletons_.push_back(singleton->type());
215 auto creationOrder = creationOrder_.wlock();
216 creationOrder->clear();
220 void SingletonVault::reenableInstances() {
221 auto state = state_.wlock();
223 stateCheck(SingletonVaultState::Quiescing, *state);
225 state->state = SingletonVaultState::Running;
228 void SingletonVault::scheduleDestroyInstances() {
229 // Add a dependency on folly::ThreadLocal to make sure all its static
230 // singletons are initalized first.
231 threadlocal_detail::StaticMeta<void, void>::instance();
233 class SingletonVaultDestructor {
235 ~SingletonVaultDestructor() {
236 SingletonVault::singleton()->destroyInstances();
240 // Here we intialize a singleton, which calls destroyInstances in its
241 // destructor. Because of singleton destruction order - it will be destroyed
242 // before all the singletons, which were initialized before it and after all
243 // the singletons initialized after it.
244 static SingletonVaultDestructor singletonVaultDestructor;