New feature support in folly::AtomicHash*
[folly.git] / folly / AtomicHashArray.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
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.
24  *
25  *  Check out AtomicHashMap.h for more thorough documentation on perf and
26  *  general pros and cons relative to other hash maps.
27  *
28  *  @author Spencer Ahrens <sahrens@fb.com>
29  *  @author Jordan DeLong <delong.j@fb.com>
30  */
31
32 #ifndef FOLLY_ATOMICHASHARRAY_H_
33 #define FOLLY_ATOMICHASHARRAY_H_
34
35 #include <atomic>
36
37 #include <boost/iterator/iterator_facade.hpp>
38 #include <boost/noncopyable.hpp>
39
40 #include "folly/Hash.h"
41 #include "folly/ThreadCachedInt.h"
42
43 namespace folly {
44
45 template <class KeyT, class ValueT,
46           class HashFcn = std::hash<KeyT>, class EqualFcn = std::equal_to<KeyT>>
47 class AtomicHashMap;
48
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.");
58  public:
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;
68
69   const size_t  capacity_;
70   const size_t  maxEntries_;
71   const KeyT    kEmptyKey_;
72   const KeyT    kLockedKey_;
73   const KeyT    kErasedKey_;
74
75   template<class ContT, class IterVal>
76   struct aha_iterator;
77
78   typedef aha_iterator<const AtomicHashArray,const value_type> const_iterator;
79   typedef aha_iterator<AtomicHashArray,value_type> iterator;
80
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
84   // after yourself.
85   static void destroy(AtomicHashArray*);
86
87  private:
88   const size_t  kAnchorMask_;
89
90   struct Deleter {
91     void operator()(AtomicHashArray* ptr) {
92       AtomicHashArray::destroy(ptr);
93     }
94   };
95
96  public:
97   typedef std::unique_ptr<AtomicHashArray, Deleter> SmartPtr;
98
99   /*
100    * create --
101    *
102    *   Creates AtomicHashArray objects.  Use instead of constructor/destructor.
103    *
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
107    *   them when growing.
108    *
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
113    *   maxLoadFactor.
114    *
115    *   Create returns an AHA::SmartPtr which is a unique_ptr with a custom
116    *   deleter to make sure everything is cleaned up properly.
117    */
118   struct Config {
119     KeyT   emptyKey;
120     KeyT   lockedKey;
121     KeyT   erasedKey;
122     double maxLoadFactor;
123     double growthFactor;
124     int    entryCountThreadCacheSize;
125     size_t capacity; // if positive, overrides maxLoadFactor
126
127     constexpr Config() : emptyKey((KeyT)-1),
128                          lockedKey((KeyT)-2),
129                          erasedKey((KeyT)-3),
130                          maxLoadFactor(0.8),
131                          growthFactor(-1),
132                          entryCountThreadCacheSize(1000),
133                          capacity(0) {}
134   };
135
136   static const Config defaultConfig;
137   static SmartPtr create(size_t maxSize, const Config& = defaultConfig);
138
139   iterator find(KeyT k) {
140     return iterator(this, findInternal(k).idx);
141   }
142   const_iterator find(KeyT k) const {
143     return const_cast<AtomicHashArray*>(this)->find(k);
144   }
145
146   /*
147    * insert --
148    *
149    *   Returns a pair with iterator to the element at r.first and bool success.
150    *   Retrieve the index with ret.first.getIndex().
151    *
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.
156    */
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);
160   }
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);
164   }
165
166   // returns the number of elements erased - should never exceed 1
167   size_t erase(KeyT k);
168
169   // clears all keys and values in the map and resets all counters.  Not thread
170   // safe.
171   void clear();
172
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);
178   }
179
180   bool empty() const { return size() == 0; }
181
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_); }
186
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);
193   }
194   const_iterator findAt(uint32_t idx) const {
195     return const_cast<AtomicHashArray*>(this)->findAt(idx);
196   }
197
198   iterator makeIter(size_t idx) { return iterator(this, idx); }
199   const_iterator makeIter(size_t idx) const {
200     return const_iterator(this, idx);
201   }
202
203   // The max load factor allowed for this map
204   double maxLoadFactor() const { return ((double) maxEntries_) / capacity_; }
205
206   void setEntryCountThreadCacheSize(uint32_t newSize) {
207     numEntries_.setCacheSize(newSize);
208     numPendingEntries_.setCacheSize(newSize);
209   }
210
211   int getEntryCountThreadCacheSize() const {
212     return numEntries_.getCacheSize();
213   }
214
215   /* Private data and helper functions... */
216
217  private:
218   friend class AtomicHashMap<KeyT,ValueT,HashFcn,EqualFcn>;
219
220   struct SimpleRetT { size_t idx; bool success;
221     SimpleRetT(size_t i, bool s) : idx(i), success(s) {}
222     SimpleRetT() {}
223   };
224
225   template <class T>
226   SimpleRetT insertInternal(KeyT key, T&& value);
227
228   SimpleRetT findInternal(const KeyT key);
229
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");
236     return
237       const_cast<std::atomic<KeyT>*>(
238         reinterpret_cast<std::atomic<KeyT> const*>(&r.first));
239   }
240
241   static KeyT relaxedLoadKey(const value_type& r) {
242     return cellKeyPtr(r)->load(std::memory_order_relaxed);
243   }
244
245   static KeyT acquireLoadKey(const value_type& r) {
246     return cellKeyPtr(r)->load(std::memory_order_acquire);
247   }
248
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
254   // accurate.
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
259
260   value_type cells_[0];  // This must be the last field of this class
261
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);
266
267   ~AtomicHashArray() {}
268
269   inline void unlockCell(value_type* const cell, KeyT newKey) {
270     cellKeyPtr(*cell)->store(newKey, std::memory_order_release);
271   }
272
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);
277   }
278
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_;
283   }
284
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_);
290   }
291 }; // AtomicHashArray
292
293 } // namespace folly
294
295 #include "AtomicHashArray-inl.h"
296
297 #endif // FOLLY_ATOMICHASHARRAY_H_