1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2014 UnitedStack <haomai@unitedstack.com>
8 * Author: Haomai Wang <haomaiwang@gmail.com>
10 * This is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License version 2.1, as published by the Free Software
13 * Foundation. See file COPYING.
17 #ifndef CEPH_RANDOMCACHE_H
18 #define CEPH_RANDOMCACHE_H
20 #include "common/Mutex.h"
21 #include "include/compat.h"
22 #include "include/unordered_map.h"
25 // Although This is a ramdom cache implementation, here still consider to make
26 // the trim progress more reasonable. Each item owns its lookup frequency,
27 // when the cache is full it will randomly pick up several items and compare the
28 // frequency associated with. The least frequency of items will be evicted.
29 template <class K, class V>
31 // The first element of pair is the frequency of item, it's used to evict item
32 ceph::unordered_map<K, pair<uint64_t, V> > contents;
37 // When cache reach full, consider to evict a certain number of items
38 static const uint64_t EVICT_COUNT = 5;
39 // Avoid too much overhead on comparing items's frequency, the number of
40 // compare items is expected to small.
41 static const uint64_t COMPARE_COUNT = 3;
43 // In order to make evict cache progress more lightweight and effective,
44 // several items are expected to evicted in one call
45 void trim_cache(uint64_t evict_count) {
46 typename ceph::unordered_map<K, pair<uint64_t, V> >::iterator it = contents.find(last_trim_key);
47 uint64_t total_compare = evict_count * COMPARE_COUNT;
48 map<uint64_t, K> candidates;
50 while (total_compare--) {
51 if (it == contents.end()) {
52 it = contents.begin();
55 candidates[it->second.first] = it->first;
58 if (it != contents.end())
59 last_trim_key = it->first;
61 last_trim_key = contents.begin()->first;
63 for (typename map<uint64_t, K>::iterator j = candidates.begin(); j != candidates.end(); j++) {
64 contents.erase(j->second);
72 RandomCache(size_t max_size=20) : lock("RandomCache::lock"),
79 Mutex::Locker l(lock);
83 void set_size(size_t new_size) {
84 Mutex::Locker l(lock);
86 if (max_size <= contents.size()) {
87 trim_cache(contents.size() - max_size);
91 bool lookup(K key, V *out) {
92 Mutex::Locker l(lock);
93 typename ceph::unordered_map<K, pair<uint64_t, V> >::iterator it = contents.find(key);
94 if (it != contents.end()) {
96 *out = it->second.second;
102 void add(K key, V value) {
103 Mutex::Locker l(lock);
104 if (max_size <= contents.size()) {
105 trim_cache(EVICT_COUNT);
107 contents[key] = make_pair(1, value);