Skip to content

Commit

Permalink
fix managed cache invalidate not being lazy (#88)
Browse files Browse the repository at this point in the history
  • Loading branch information
strokyl authored Jun 20, 2022
1 parent 4ec7a42 commit dfe47d3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion zio-cache/shared/src/main/scala/zio/cache/ManagedCache.scala
Original file line number Diff line number Diff line change
Expand Up @@ -238,12 +238,13 @@ object ManagedCache {
finalManaged.flatMap(_.use_(ZIO.unit))
}

override def invalidate(k: Key): UIO[Unit] =
override def invalidate(k: Key): UIO[Unit] = UIO.effectSuspendTotal {
map.remove(k) match {
case complete @ MapValue.Complete(_, _, _, _, _) => complete.releaseOwner
case MapValue.Refreshing(_, complete) => complete.releaseOwner
case _ => UIO.unit
}
}

override def invalidateAll: UIO[Unit] =
ZIO.foreachPar_(map.keySet().asScala)(invalidate)
Expand Down
26 changes: 26 additions & 0 deletions zio-cache/shared/src/test/scala/zio/cache/ManagedCacheSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,32 @@ object ManagedCacheSpec extends DefaultRunnableSpec {
}
} yield result
},
testM("invalidate should not invalidate anything before effect is evaluated") {
for {
observablesResource <- ObservableResourceForTest.makeUnit
managedCache =
ManagedCache.make(
capacity = 4,
timeToLive = Duration.Infinity,
lookup = ManagedLookup((_: Unit) => observablesResource.managed)
)
result <-
managedCache.use { cache =>
for {
_ <- cache.get(key = ()).use_(ZIO.unit)
invalidateEffect = cache.invalidate(key = ())
cacheContainsKey42BeforeInvalidate <- cache.contains(key = ())
resourceNotCleanedBeforeInvalidate <- observablesResource.assertAcquiredOnceAndNotCleaned
_ <- cache.get(()).use_(ZIO.unit)
_ <- invalidateEffect
cacheContainsKey42AfterInvalidate <- cache.contains(key = ())
resourceCleanedAfterInvalidate <- observablesResource.assertAcquiredOnceAndCleaned
} yield assert(cacheContainsKey42BeforeInvalidate)(isTrue) && assert(cacheContainsKey42AfterInvalidate)(
isFalse
) && resourceNotCleanedBeforeInvalidate && resourceCleanedAfterInvalidate
}
} yield result
},
testM("invalidateAll should properly remove and clean all resource from the cache") {
val capacity = 100
for {
Expand Down

0 comments on commit dfe47d3

Please sign in to comment.