diff --git a/quartz/src/main/java/com/vitorpamplona/quartz/utils/LargeSoftCache.kt b/quartz/src/main/java/com/vitorpamplona/quartz/utils/LargeSoftCache.kt index 995c0701c..947633789 100644 --- a/quartz/src/main/java/com/vitorpamplona/quartz/utils/LargeSoftCache.kt +++ b/quartz/src/main/java/com/vitorpamplona/quartz/utils/LargeSoftCache.kt @@ -31,18 +31,24 @@ class LargeSoftCache : CacheOperations { fun get(key: K): V? { val softRef = cache.get(key) - val value = softRef?.get() + if (softRef == null) return null + val value = softRef.get() return if (value != null) { value } else { - cache.remove(key) + cache.remove(key, softRef) null } } fun remove(key: K) = cache.remove(key) + fun removeIf( + key: K, + value: WeakReference, + ) = cache.remove(key, value) + override fun size() = cache.size fun isEmpty() = cache.isEmpty() @@ -95,14 +101,14 @@ class LargeSoftCache : CacheOperations { * this method can be called periodically or when memory pressure is high. */ fun cleanUp() { - val keysToRemove = mutableListOf() - forEach { key, softRef -> - if (softRef == null) { - keysToRemove.add(key) + val keysToRemove = mutableMapOf>() + cache.forEach { key, softRef -> + if (softRef.get() == null) { + keysToRemove.put(key, softRef) } } - keysToRemove.forEach { key -> - cache.remove(key) + keysToRemove.forEach { key, value -> + cache.remove(key, value) println("Cleaned up entry for key: $key (object was garbage collected)") } println("Cache cleanup completed. Remaining size: ${cache.size}") @@ -122,7 +128,7 @@ class LargeSoftCache : CacheOperations { ) { val value = ref.get() if (value == null) { - cache.remove(k) + cache.removeIf(k, ref) } else { inner.accept(k, value) }