Skip to content

Commit

Permalink
Do Not Increment Cache Hits For Expired Entries (#163)
Browse files Browse the repository at this point in the history
* do not increment cache hits for expired entries

* format
  • Loading branch information
adamgfraser authored Oct 19, 2023
1 parent 3ce1022 commit 8a2586f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
2 changes: 1 addition & 1 deletion zio-cache/shared/src/main/scala/zio/cache/Cache.scala
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,11 @@ object Cache {
promise.await
case MapValue.Complete(key, exit, _, timeToLive) =>
trackAccess(key)
trackHit()
if (hasExpired(timeToLive)) {
map.remove(k, value)
get(in)
} else {
trackHit()
ZIO.done(exit)
}
case MapValue.Refreshing(
Expand Down
17 changes: 16 additions & 1 deletion zio-cache/shared/src/test/scala/zio/cache/CacheSpec.scala
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package zio.cache

import zio._
import zio.test.Assertion._
import zio.test._
import zio.{Duration, Ref, Scope, UIO, ZIO, duration2DurationOps}

object CacheSpec extends ZIOSpecDefault {

def hash(x: Int): Int => UIO[Int] =
y => ZIO.succeed((x ^ y).hashCode)

val identity: Int => UIO[Int] =
ZIO.succeed(_)

def spec: Spec[TestEnvironment with Scope, Any] = suite("CacheSpec")(
test("cacheStats") {
check(Gen.int) { salt =>
Expand Down Expand Up @@ -142,6 +145,18 @@ object CacheSpec extends ZIOSpecDefault {
size <- cache.size
} yield assertTrue(size == 10)
}
},
test("cache hits should not be incremented for expired entries") {
for {
cache <- Cache.make(100, 1.second, Lookup(identity))
_ <- cache.get(42)
_ <- TestClock.adjust(2.seconds)
_ <- cache.get(42)
cacheStats <- cache.cacheStats
hits = cacheStats.hits
misses = cacheStats.misses
} yield assertTrue(hits == 0L) &&
assertTrue(misses == 2L)
}
)
}

0 comments on commit 8a2586f

Please sign in to comment.