Skip to content

Commit

Permalink
do not increment cache hits for expired entries
Browse files Browse the repository at this point in the history
  • Loading branch information
adamgfraser committed Oct 19, 2023
1 parent 3ce1022 commit 490e9b3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 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
19 changes: 17 additions & 2 deletions 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.test.Assertion._
import zio._
import zio.test._
import zio.{Duration, Ref, Scope, UIO, ZIO, duration2DurationOps}
import zio.test.Assertion._

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 490e9b3

Please sign in to comment.