File tree Expand file tree Collapse file tree 3 files changed +39
-0
lines changed Expand file tree Collapse file tree 3 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -81,6 +81,13 @@ class Cache {
81
81
// its cache keys.
82
82
virtual uint64_t NewId () = 0;
83
83
84
+ // Remove all cache entries that are not actively in use. Memory-constrained
85
+ // applications may wish to call this method to reduce memory usage.
86
+ // Default implementation of Prune() does nothing. Subclasses are strongly
87
+ // encouraged to override the default implementation. A future release of
88
+ // leveldb may change Prune() to a pure abstract method.
89
+ virtual void Prune () {}
90
+
84
91
private:
85
92
void LRU_Remove (Handle* e);
86
93
void LRU_Append (Handle* e);
Original file line number Diff line number Diff line change @@ -147,6 +147,7 @@ class LRUCache {
147
147
Cache::Handle* Lookup (const Slice& key, uint32_t hash);
148
148
void Release (Cache::Handle* handle);
149
149
void Erase (const Slice& key, uint32_t hash);
150
+ void Prune ();
150
151
151
152
private:
152
153
void LRU_Remove (LRUHandle* e);
@@ -264,6 +265,19 @@ void LRUCache::Erase(const Slice& key, uint32_t hash) {
264
265
}
265
266
}
266
267
268
+ void LRUCache::Prune () {
269
+ MutexLock l (&mutex_);
270
+ for (LRUHandle* e = lru_.next ; e != &lru_; ) {
271
+ LRUHandle* next = e->next ;
272
+ if (e->refs == 1 ) {
273
+ table_.Remove (e->key (), e->hash );
274
+ LRU_Remove (e);
275
+ Unref (e);
276
+ }
277
+ e = next;
278
+ }
279
+ }
280
+
267
281
static const int kNumShardBits = 4 ;
268
282
static const int kNumShards = 1 << kNumShardBits ;
269
283
@@ -314,6 +328,11 @@ class ShardedLRUCache : public Cache {
314
328
MutexLock l (&id_mutex_);
315
329
return ++(last_id_);
316
330
}
331
+ virtual void Prune () {
332
+ for (int s = 0 ; s < kNumShards ; s++) {
333
+ shard_[s].Prune ();
334
+ }
335
+ }
317
336
};
318
337
319
338
} // end anonymous namespace
Original file line number Diff line number Diff line change @@ -179,6 +179,19 @@ TEST(CacheTest, NewId) {
179
179
ASSERT_NE (a, b);
180
180
}
181
181
182
+ TEST (CacheTest, Prune) {
183
+ Insert (1 , 100 );
184
+ Insert (2 , 200 );
185
+
186
+ Cache::Handle* handle = cache_->Lookup (EncodeKey (1 ));
187
+ ASSERT_TRUE (handle);
188
+ cache_->Prune ();
189
+ cache_->Release (handle);
190
+
191
+ ASSERT_EQ (100 , Lookup (1 ));
192
+ ASSERT_EQ (-1 , Lookup (2 ));
193
+ }
194
+
182
195
} // namespace leveldb
183
196
184
197
int main (int argc, char ** argv) {
You can’t perform that action at this time.
0 commit comments