11package org.dweb_browser.pure.image.compose
22
33import kotlinx.coroutines.CoroutineScope
4- import kotlinx.coroutines.delay
5- import kotlinx.coroutines.launch
64import org.dweb_browser.helper.SafeHashMap
5+ import org.dweb_browser.helper.SafeLinkList
6+ import org.dweb_browser.helper.trueAlso
77
88data class CacheItem <T >(
99 val task : LoaderTask ,
@@ -14,48 +14,35 @@ data class CacheItem<T>(
1414 internal var hot = 30f
1515}
1616
17- class LoaderCacheMap <T : Any >(scope : CoroutineScope , cacheSize : Int = 10 ) {
17+ class LoaderCacheMap <T : Any >(scope : CoroutineScope , var cacheSize : Int = 10 ) {
1818 private val map = SafeHashMap <String , CacheItem <T >>()
19-
20- init {
21- scope.launch {
22- while (true ) {
23- delay(5000 )
24- if (map.size <= cacheSize) {
25- return @launch
26- }
27- val willRemoves = mutableListOf<MutableMap .MutableEntry <String , CacheItem <T >>>()
28- map.sync {
29- for (item in map) {
30- item.value.hot - = 5f
31- if (item.value.hot <= 0 ) {
32- willRemoves.add(item)
33- }
34- }
35- willRemoves.sortBy { it.value.hot }
36- for ((key) in willRemoves) {
37- this .remove(key)
38- if (this .size <= cacheSize) {
39- break
40- }
41- }
42- }
43- }
44- }
45- }
19+ private val lruList = SafeLinkList <CacheItem <T >>()
4620
4721 fun get (task : LoaderTask ): T ? =
48- map[task.key]?.result
22+ map[task.key]?.let {
23+ lruList.remove(it)
24+ lruList.add(0 , it)
25+ it.result
26+ }
4927
5028 fun save (cache : CacheItem <T >) {
5129 map[cache.key] = cache
30+ lruList.add(0 , cache)
31+ while (map.size > cacheSize) {
32+ val willRemove = lruList.removeLast()
33+ map.remove(willRemove.key)
34+ }
5235 }
5336
5437 fun delete (task : LoaderTask , result : CacheItem <T >? = null) {
5538 if (result == null ) {
56- map.remove(task.key)
39+ map.remove(task.key)?.also {
40+ lruList.remove(it)
41+ }
5742 } else {
58- map.remove(task.key, result)
43+ map.remove(task.key, result).trueAlso {
44+ lruList.remove(result)
45+ }
5946 }
6047 }
6148}
0 commit comments