OmniSciDB  0264ff685a
HashTableCache.h
Go to the documentation of this file.
1 /*
2  * Copyright 2020 OmniSci, 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 #pragma once
18 
19 #include <functional>
20 #include <mutex>
21 #include <vector>
22 
23 #include "Logger/Logger.h"
24 
25 template <class K, class V>
27  public:
29 
30  std::function<void()> getCacheInvalidator() {
31  return [this]() -> void {
32  std::lock_guard<std::mutex> guard(mutex_);
33  VLOG(1) << "Invalidating " << contents_.size() << " cached hash tables.";
34  contents_.clear();
35  };
36  }
37 
38  V getCachedHashTable(const size_t idx) {
39  std::lock_guard<std::mutex> guard(mutex_);
40  CHECK_LT(idx, contents_.size());
41  return contents_.at(idx).second;
42  }
43 
45  std::lock_guard<std::mutex> guard(mutex_);
46  return contents_.size();
47  }
48 
49  void clear() {
50  std::lock_guard<std::mutex> guard(mutex_);
51  contents_.clear();
52  }
53 
54  void insert(const K& key, V& hash_table) {
55  std::lock_guard<std::mutex> guard(mutex_);
56  for (auto& kv : contents_) {
57  if (kv.first == key) {
58  auto& cached_hash_table = kv.second;
59  cached_hash_table = hash_table;
60  return;
61  }
62  }
63  contents_.emplace_back(key, hash_table);
64  }
65 
66  // makes a copy
67  V get(const K& key) {
68  std::lock_guard<std::mutex> guard(mutex_);
69  for (const auto& kv : contents_) {
70  if (kv.first == key) {
71  return kv.second;
72  }
73  }
74  return nullptr;
75  }
76 
77  private:
78  std::vector<std::pair<K, V>> contents_;
79  std::mutex mutex_;
80 };
V getCachedHashTable(const size_t idx)
std::function< void()> getCacheInvalidator()
void insert(const K &key, V &hash_table)
#define CHECK_LT(x, y)
Definition: Logger.h:207
std::mutex mutex_
size_t getNumberOfCachedHashTables()
std::vector< std::pair< K, V > > contents_
#define VLOG(n)
Definition: Logger.h:291