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.
17 #include <gtest/gtest.h>
23 #include <folly/AtomicHashMap.h>
24 #include <folly/ScopeGuard.h>
25 #include <folly/Memory.h>
30 explicit MyObject(int i) : i(i) {}
34 typedef folly::AtomicHashMap<int,std::shared_ptr<MyObject>> MyMap;
35 typedef std::lock_guard<std::mutex> Guard;
37 std::unique_ptr<MyMap> newMap() { return folly::make_unique<MyMap>(100); }
39 struct MyObjectDirectory {
45 std::shared_ptr<MyObject> get(int key) {
46 auto val = tryGet(key);
51 std::shared_ptr<MyMap> cur;
57 auto ret = cur->insert(key, std::make_shared<MyObject>(key));
58 return ret.first->second;
61 std::shared_ptr<MyObject> tryGet(int key) {
62 std::shared_ptr<MyMap> cur;
63 std::shared_ptr<MyMap> prev;
70 auto it = cur->find(key);
71 if (it != cur->end()) {
76 if (it != prev->end()) {
77 auto ret = cur->insert(key, it->second);
78 return ret.first->second;
85 std::shared_ptr<MyMap> cur(newMap());
93 std::shared_ptr<MyMap> cur_;
94 std::shared_ptr<MyMap> prev_;
99 //////////////////////////////////////////////////////////////////////
102 * This test case stresses ThreadLocal allocation/deallocation heavily
103 * via ThreadCachedInt and AtomicHashMap, and a bunch of other
106 TEST(AHMIntStressTest, Test) {
107 auto const objs = new MyObjectDirectory();
108 SCOPE_EXIT { delete objs; };
110 std::vector<std::thread> threads;
111 for (int threadId = 0; threadId < 64; ++threadId) {
112 threads.emplace_back(
114 for (int recycles = 0; recycles < 500; ++recycles) {
115 for (int i = 0; i < 10; i++) {
116 auto val = objs->get(i);
125 for (auto& t : threads) t.join();