WebDAV memory cache: store values using SoftReference (bitfireAT/davx5#515)

so that the values can be free if there's not enough memory
This commit is contained in:
Ricki Hirner 2024-01-11 13:45:56 +01:00
parent 357cf09be7
commit 3c4601f7a1
2 changed files with 7 additions and 4 deletions

View file

@ -5,12 +5,15 @@
package at.bitfire.davdroid.webdav.cache
import android.util.LruCache
import java.lang.ref.SoftReference
/**
* Simple thread-safe cache class based on [LruCache] that provides atomic [getOrPut]
* and [getOrPutIfNotNull] methods.
*
* Values are stored using [SoftReference] so that they can be removed if there's not enough memory.
*/
class ExtendedLruCache<K, V>(maxSize: Int) : LruCache<K, V>(maxSize) {
class ExtendedLruCache<K, V>(maxSize: Int) : LruCache<K, SoftReference<V>>(maxSize) {
/**
* Retrieves data from the cache, if available. Otherwise calls a callback to
@ -24,13 +27,13 @@ class ExtendedLruCache<K, V>(maxSize: Int) : LruCache<K, V>(maxSize) {
@Synchronized
fun getOrPut(key: K, compute: () -> V): V {
// use cached value, if possible
val data = get(key)
val data = get(key)?.get()
if (data != null)
return data
// compute new value otherwise
val newValue = compute()
put(key, newValue)
put(key, SoftReference(newValue))
return newValue
}

View file

@ -18,7 +18,7 @@ typealias PageCache = ExtendedLruCache<PageCacheBuilder.PageIdentifier, ByteArra
object PageCacheBuilder {
const val MAX_PAGE_SIZE = 2 * FileUtils.ONE_MB.toInt()
private const val MAX_ENTRIES = 2 // cache up to 2 pages (4 MB in total) in memory
private const val MAX_ENTRIES = 3 // cache up to 3 pages (6 MB in total) in memory
private var _cache: WeakReference<PageCache>? = null