mirror of
https://github.com/bitfireAT/davx5-ose
synced 2024-07-22 03:01:24 +00:00
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:
parent
357cf09be7
commit
3c4601f7a1
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in a new issue