2 * Copyright 2013 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.
18 * AtomicHashArray is the building block for AtomicHashMap. It provides the
19 * core lock-free functionality, but is limitted by the fact that it cannot
20 * grow past it's initialization size and is a little more awkward (no public
21 * constructor, for example). If you're confident that you won't run out of
22 * space, don't mind the awkardness, and really need bare-metal performance,
23 * feel free to use AHA directly.
25 * Check out AtomicHashMap.h for more thorough documentation on perf and
26 * general pros and cons relative to other hash maps.
28 * @author Spencer Ahrens <sahrens@fb.com>
29 * @author Jordan DeLong <delong.j@fb.com>
32 #ifndef FOLLY_ATOMICHASHARRAY_H_
33 #define FOLLY_ATOMICHASHARRAY_H_
37 #include <boost/iterator/iterator_facade.hpp>
38 #include <boost/noncopyable.hpp>
40 #include "folly/Hash.h"
41 #include "folly/ThreadCachedInt.h"
45 template <class KeyT, class ValueT,
46 class HashFcn = std::hash<KeyT>, class EqualFcn = std::equal_to<KeyT>>
49 template <class KeyT, class ValueT,
50 class HashFcn = std::hash<KeyT>, class EqualFcn = std::equal_to<KeyT>>
51 class AtomicHashArray : boost::noncopyable {
52 static_assert((std::is_convertible<KeyT,int32_t>::value ||
53 std::is_convertible<KeyT,int64_t>::value ||
54 std::is_convertible<KeyT,const void*>::value),
55 "You are trying to use AtomicHashArray with disallowed key "
56 "types. You must use atomically compare-and-swappable integer "
57 "keys, or a different container class.");
59 typedef KeyT key_type;
60 typedef ValueT mapped_type;
61 typedef std::pair<const KeyT, ValueT> value_type;
62 typedef std::size_t size_type;
63 typedef std::ptrdiff_t difference_type;
64 typedef value_type& reference;
65 typedef const value_type& const_reference;
66 typedef value_type* pointer;
67 typedef const value_type* const_pointer;
69 const size_t capacity_;
70 const size_t maxEntries_;
71 const KeyT kEmptyKey_;
72 const KeyT kLockedKey_;
73 const KeyT kErasedKey_;
75 template<class ContT, class IterVal>
78 typedef aha_iterator<const AtomicHashArray,const value_type> const_iterator;
79 typedef aha_iterator<AtomicHashArray,value_type> iterator;
81 // You really shouldn't need this if you use the SmartPtr provided by create,
82 // but if you really want to do something crazy like stick the released
83 // pointer into a DescriminatedPtr or something, you'll need this to clean up
85 static void destroy(AtomicHashArray*);
88 const size_t kAnchorMask_;
91 void operator()(AtomicHashArray* ptr) {
92 AtomicHashArray::destroy(ptr);
97 typedef std::unique_ptr<AtomicHashArray, Deleter> SmartPtr;
102 * Creates AtomicHashArray objects. Use instead of constructor/destructor.
104 * We do things this way in order to avoid the perf penalty of a second
105 * pointer indirection when composing these into AtomicHashMap, which needs
106 * to store an array of pointers so that it can perform atomic operations on
109 * Instead of a mess of arguments, we take a max size and a Config struct to
110 * simulate named ctor parameters. The Config struct has sensible defaults
111 * for everything, but is overloaded - if you specify a positive capacity,
112 * that will be used directly instead of computing it based on
115 * Create returns an AHA::SmartPtr which is a unique_ptr with a custom
116 * deleter to make sure everything is cleaned up properly.
122 double maxLoadFactor;
124 int entryCountThreadCacheSize;
125 size_t capacity; // if positive, overrides maxLoadFactor
127 constexpr Config() : emptyKey((KeyT)-1),
132 entryCountThreadCacheSize(1000),
136 static const Config defaultConfig;
137 static SmartPtr create(size_t maxSize, const Config& = defaultConfig);
139 iterator find(KeyT k) {
140 return iterator(this, findInternal(k).idx);
142 const_iterator find(KeyT k) const {
143 return const_cast<AtomicHashArray*>(this)->find(k);
149 * Returns a pair with iterator to the element at r.first and bool success.
150 * Retrieve the index with ret.first.getIndex().
152 * Fails on key collision (does not overwrite) or if map becomes
153 * full, at which point no element is inserted, iterator is set to end(),
154 * and success is set false. On collisions, success is set false, but the
155 * iterator is set to the existing entry.
157 std::pair<iterator,bool> insert(const value_type& r) {
158 SimpleRetT ret = insertInternal(r.first, r.second);
159 return std::make_pair(iterator(this, ret.idx), ret.success);
161 std::pair<iterator,bool> insert(value_type&& r) {
162 SimpleRetT ret = insertInternal(r.first, std::move(r.second));
163 return std::make_pair(iterator(this, ret.idx), ret.success);
166 // returns the number of elements erased - should never exceed 1
167 size_t erase(KeyT k);
169 // clears all keys and values in the map and resets all counters. Not thread
173 // Exact number of elements in the map - note that readFull() acquires a
174 // mutex. See folly/ThreadCachedInt.h for more details.
175 size_t size() const {
176 return numEntries_.readFull() -
177 numErases_.load(std::memory_order_relaxed);
180 bool empty() const { return size() == 0; }
182 iterator begin() { return iterator(this, 0); }
183 iterator end() { return iterator(this, capacity_); }
184 const_iterator begin() const { return const_iterator(this, 0); }
185 const_iterator end() const { return const_iterator(this, capacity_); }
187 // See AtomicHashMap::findAt - access elements directly
188 // WARNING: The following 2 functions will fail silently for hashtable
189 // with capacity > 2^32
190 iterator findAt(uint32_t idx) {
191 DCHECK_LT(idx, capacity_);
192 return iterator(this, idx);
194 const_iterator findAt(uint32_t idx) const {
195 return const_cast<AtomicHashArray*>(this)->findAt(idx);
198 iterator makeIter(size_t idx) { return iterator(this, idx); }
199 const_iterator makeIter(size_t idx) const {
200 return const_iterator(this, idx);
203 // The max load factor allowed for this map
204 double maxLoadFactor() const { return ((double) maxEntries_) / capacity_; }
206 void setEntryCountThreadCacheSize(uint32_t newSize) {
207 numEntries_.setCacheSize(newSize);
208 numPendingEntries_.setCacheSize(newSize);
211 int getEntryCountThreadCacheSize() const {
212 return numEntries_.getCacheSize();
215 /* Private data and helper functions... */
218 friend class AtomicHashMap<KeyT,ValueT,HashFcn,EqualFcn>;
220 struct SimpleRetT { size_t idx; bool success;
221 SimpleRetT(size_t i, bool s) : idx(i), success(s) {}
226 SimpleRetT insertInternal(KeyT key, T&& value);
228 SimpleRetT findInternal(const KeyT key);
230 static std::atomic<KeyT>* cellKeyPtr(const value_type& r) {
231 // We need some illegal casting here in order to actually store
232 // our value_type as a std::pair<const,>. But a little bit of
233 // undefined behavior never hurt anyone ...
234 static_assert(sizeof(std::atomic<KeyT>) == sizeof(KeyT),
235 "std::atomic is implemented in an unexpected way for AHM");
237 const_cast<std::atomic<KeyT>*>(
238 reinterpret_cast<std::atomic<KeyT> const*>(&r.first));
241 static KeyT relaxedLoadKey(const value_type& r) {
242 return cellKeyPtr(r)->load(std::memory_order_relaxed);
245 static KeyT acquireLoadKey(const value_type& r) {
246 return cellKeyPtr(r)->load(std::memory_order_acquire);
249 // Fun with thread local storage - atomic increment is expensive
250 // (relatively), so we accumulate in the thread cache and periodically
251 // flush to the actual variable, and walk through the unflushed counts when
252 // reading the value, so be careful of calling size() too frequently. This
253 // increases insertion throughput several times over while keeping the count
255 ThreadCachedInt<int64_t> numEntries_; // Successful key inserts
256 ThreadCachedInt<int64_t> numPendingEntries_; // Used by insertInternal
257 std::atomic<int64_t> isFull_; // Used by insertInternal
258 std::atomic<int64_t> numErases_; // Successful key erases
260 value_type cells_[0]; // This must be the last field of this class
262 // Force constructor/destructor private since create/destroy should be
263 // used externally instead
264 AtomicHashArray(size_t capacity, KeyT emptyKey, KeyT lockedKey,
265 KeyT erasedKey, double maxLoadFactor, size_t cacheSize);
267 ~AtomicHashArray() {}
269 inline void unlockCell(value_type* const cell, KeyT newKey) {
270 cellKeyPtr(*cell)->store(newKey, std::memory_order_release);
273 inline bool tryLockCell(value_type* const cell) {
274 KeyT expect = kEmptyKey_;
275 return cellKeyPtr(*cell)->compare_exchange_strong(expect, kLockedKey_,
276 std::memory_order_acq_rel);
279 inline size_t keyToAnchorIdx(const KeyT k) const {
280 const size_t hashVal = HashFcn()(k);
281 const size_t probe = hashVal & kAnchorMask_;
282 return LIKELY(probe < capacity_) ? probe : hashVal % capacity_;
285 inline size_t probeNext(size_t idx, size_t numProbes) {
286 //idx += numProbes; // quadratic probing
287 idx += 1; // linear probing
288 // Avoid modulus because it's slow
289 return LIKELY(idx < capacity_) ? idx : (idx - capacity_);
291 }; // AtomicHashArray
295 #include "AtomicHashArray-inl.h"
297 #endif // FOLLY_ATOMICHASHARRAY_H_