Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that accesses queue is empty when calling trackAccess #177

Merged
merged 1 commit into from
Feb 24, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 28 additions & 21 deletions zio-cache/shared/src/main/scala/zio/cache/Cache.scala
Original file line number Diff line number Diff line change
Expand Up @@ -286,32 +286,39 @@ object Cache {
clock.unsafe.instant()(Unsafe).isAfter(timeToLive)

private def trackAccess(key: MapKey[Key]): Unit = {
accesses.offer(key)
if (updating.compareAndSet(false, true)) {
var loop = true
while (loop) {
val key = accesses.poll(null)
if (key ne null) {
keys.add(key)
} else {
loop = false
@tailrec def loop(): Unit = {
if (updating.compareAndSet(false, true)) {
var loop = true
while (loop) {
val key = accesses.poll(null)
if (key ne null) {
keys.add(key)
} else {
loop = false
}
}
}
var size = map.size
loop = size > capacity
while (loop) {
val key = keys.remove()
if (key ne null) {
if (map.remove(key.value) ne null) {
size -= 1
loop = size > capacity
var size = map.size
loop = size > capacity
while (loop) {
val key = keys.remove()
if (key ne null) {
if (map.remove(key.value) ne null) {
size -= 1
loop = size > capacity
}
} else {
loop = false
}
} else {
loop = false
}
updating.set(false)
}
updating.set(false)

// Someone might have added a key right after we drained the queue but before setting updating to `false`
if (!accesses.isEmpty()) loop() else ()
}

accesses.offer(key)
loop()
}

private def trackHit(): Unit =
Expand Down