Skip to content

Commit

Permalink
Merge pull request #136 from twitter/feature/fix_mutable_cache
Browse files Browse the repository at this point in the history
Fix MutableCache Bug
  • Loading branch information
johnynek committed Aug 9, 2013
2 parents 242f54f + c46f1f5 commit b835bdb
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ object MutableLRUCache {
}

class MutableLRUCache[K, V](capacity: Int) extends JMapCache[K, V](() =>
new JLinkedHashMap[K, V](capacity + 1, 0.75f) {
new JLinkedHashMap[K, V](capacity + 1, 0.75f, true) {
override protected def removeEldestEntry(eldest: JMap.Entry[K, V]) =
super.size > capacity
}) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2013 Twitter Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.twitter.storehaus.cache

import org.specs._

class MutableLRUCacheTest extends Specification {
def freshCache = MutableLRUCache[String, Int](2)

def checkCache(pairs: Seq[(String, Int)], results: Seq[Boolean]) = {
val cache = freshCache
pairs.foreach(cache += _)
pairs.map { case (k, _) => cache.contains(k) } must be_==(results)
}

"MutableLRUCache works properly with threshold 2" in {
// At capacity
checkCache(
Seq("a" -> 1, "b" -> 2),
Seq(true, true)
)
// a is touched, so b and c are evicted
checkCache(
Seq("a" -> 1, "b" -> 2, "c" -> 3, "a" -> 1, "d" -> 4),
Seq(true, false, false, true, true)
)
}
}

0 comments on commit b835bdb

Please sign in to comment.