2 * Copyright 2014 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/experimental/Singleton.h>
23 SingletonVault::~SingletonVault() { destroyInstances(); }
25 void SingletonVault::destroyInstances() {
26 std::lock_guard<std::mutex> guard(mutex_);
27 CHECK_GE(singletons_.size(), creation_order_.size());
29 for (auto type_iter = creation_order_.rbegin();
30 type_iter != creation_order_.rend();
32 auto type = *type_iter;
33 auto it = singletons_.find(type);
34 CHECK(it != singletons_.end());
35 auto& entry = it->second;
36 std::lock_guard<std::mutex> entry_guard(entry->mutex);
37 if (entry->instance.use_count() > 1) {
38 LOG(ERROR) << "Singleton of type " << type.name() << " has a living "
39 << "reference at destroyInstances time; beware! Raw pointer "
40 << "is " << entry->instance.get() << " with use_count of "
41 << entry->instance.use_count();
43 entry->instance.reset();
44 entry->state = SingletonEntryState::Dead;
45 entry->state_condvar.notify_all();
48 creation_order_.clear();
51 SingletonVault* SingletonVault::singleton() {
52 static SingletonVault vault;