2 * Copyright 2016 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.
21 #include <folly/AtomicHashMap.h>
22 #include <folly/ScopeGuard.h>
23 #include <folly/Memory.h>
24 #include <folly/portability/GTest.h>
29 explicit MyObject(int i) : i(i) {}
33 typedef folly::AtomicHashMap<int,std::shared_ptr<MyObject>> MyMap;
34 typedef std::lock_guard<std::mutex> Guard;
36 std::unique_ptr<MyMap> newMap() { return folly::make_unique<MyMap>(100); }
38 struct MyObjectDirectory {
44 std::shared_ptr<MyObject> get(int key) {
45 auto val = tryGet(key);
50 std::shared_ptr<MyMap> cur;
56 auto ret = cur->insert(key, std::make_shared<MyObject>(key));
57 return ret.first->second;
60 std::shared_ptr<MyObject> tryGet(int key) {
61 std::shared_ptr<MyMap> cur;
62 std::shared_ptr<MyMap> prev;
69 auto it = cur->find(key);
70 if (it != cur->end()) {
75 if (it != prev->end()) {
76 auto ret = cur->insert(key, it->second);
77 return ret.first->second;
84 std::shared_ptr<MyMap> cur(newMap());
92 std::shared_ptr<MyMap> cur_;
93 std::shared_ptr<MyMap> prev_;
98 //////////////////////////////////////////////////////////////////////
101 * This test case stresses ThreadLocal allocation/deallocation heavily
102 * via ThreadCachedInt and AtomicHashMap, and a bunch of other
105 TEST(AHMIntStressTest, Test) {
106 auto const objs = new MyObjectDirectory();
107 SCOPE_EXIT { delete objs; };
109 std::vector<std::thread> threads;
110 for (int threadId = 0; threadId < 64; ++threadId) {
111 threads.emplace_back(
113 for (int recycles = 0; recycles < 500; ++recycles) {
114 for (int i = 0; i < 10; i++) {
115 auto val = objs->get(i);
124 for (auto& t : threads) t.join();